C# 更改数据模板中的文本块文本

C# 更改数据模板中的文本块文本,c#,wpf,datatemplate,C#,Wpf,Datatemplate,我有一个DataTemplate,其中有一个带有2行定义的网格布局。我在第一行有一个文本框,在第二行有一个组合框 我已经在ResourceDictionary中定义了DataTemplate 这是DataTemplate的代码: <DataTemplate x:Key="myDataTemplate"> <Grid> <Grid.RowDefinitions> <RowDefinition />

我有一个DataTemplate,其中有一个带有2行定义的网格布局。我在第一行有一个文本框,在第二行有一个组合框

我已经在ResourceDictionary中定义了DataTemplate

这是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(“myDataTemplate”)

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

创建一个适合您用途的自定义数据类型(本例中的属性名为
ChannelDescription
ChannelTag
),然后将值绑定到
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>
(您的属性应该实现与此不同的
INotifyPropertyChanged
接口)

在您看来,您将拥有一个collection控件,比如一个
列表框

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


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

您应该将这两个属性绑定到ViewModel类的某些属性。在Web上搜索MVVM,并阅读MSDN上的文章。如果我多次使用该模板,则文本框和组合框将到处都有相同的内容,对吗?@Sheridan如果我没有错,它将是DataType而不是TargetType。@ethicalogics是的,甚至设置
DataType
通常也不是必需的,除非您希望自动应用DataTemplate。这似乎不是本文的目的。谢谢各位,我将更新示例,说成
DataType
@Abhishek,我们的想法是,您的
数据模板的每个实例都有一个这样的数据类型,所以它们不会有相同的值。。。我将扩展我的答案。好的,但是您示例中
DataTemplate
上的
DataType
仍然是多余的,因为
ListBox.ItemTemplate
是显式设置的。在海事组织,没有它,答案会更好,因为这只会造成混乱。
<ListBox ItemsSource="{Binding Items}" ItemTemplate="{StaticResource myDataTemplate}" />