gpt4 book ai didi

c# - 更改 DataTemplate 中存在的 TextBlock 文本

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:17 29 4
gpt4 key购买 nike

我有一个 DataTemplate,其中有一个带有 2 个 RowDefinition 的网格布局。我在第一行有一个 TextBox,在第二行有一个 ComboBox。

我已经在我的 ResourceDictionary 中定义了 DataTemplate。

这是数据模板的代码:

<DataTemplate x:Key="myDataTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Name ="txtChannelDescription" Grid.Row="0" Margin="1,1,1,1"/>
<ComboBox Name="cmbChannelTag" Grid.Row="1" IsReadOnly="True" Margin="1,1,1,1"/>
</Grid>
</DataTemplate>

我在后面的代码中使用这个 DataTemplate 作为:
(数据模板)FindResource(“我的数据模板”)

如何在运行时设置 TextBox.Text 的值和 ComboBox 的 ItemSource?我使用 DataTemplate 作为 DataGridTemplateColumn.Header 的模板。

最佳答案

创建适合您目的的自定义数据类型(在此示例中使用名为 ChannelDescriptionChannelTag 的属性),然后将值绑定(bind)到您的 DataTemplate:

<DataTemplate x:Key="myDataTemplate" DataType="{x:Type NamespacePrefix:YourDataType}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Text="{Binding ChannelDescription}" Grid.Row="0" Margin="1,1,1,1"/>
<ComboBox ItemsSource="{Binding ChannelTag}" Grid.Row="1" IsReadOnly="True"
Margin="1,1,1,1"/>
</Grid>
</DataTemplate>

它会像这样使用:

在您的 View 模型中,您将拥有一个集合属性,假设名为 Items:

public ObservableCollection<YourDataType> Items { get; set; }

(您的属性应该实现 INotifyPropertyChanged 接口(interface),这与此不同)

在您看来,您将拥有一个集合控件,比方说一个 ListBox:

<ListBox ItemsSource="{Binding Items}" ItemTemplate="{StaticResource myDataTemplate}" />

然后集合控件中的每个项目将具有相同的 DataTemplate,但值将来自 Items 中类型 YourDataType 的实例> 收藏。

关于c# - 更改 DataTemplate 中存在的 TextBlock 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18120696/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com