I have a DataTemplate in which I have a Grid layout with 2 RowDefinitions. I have a TextBox in the first row and a ComboBox in the second row.
I have defined the DataTemplate in my ResourceDictionary.
This is the code for the 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>
I am using this DataTemplate in code behind as:
(DataTemplate)FindResource("myDataTemplate")
How do I set the Value of TextBox.Text and the ItemSource of the ComboBox at runtime? I am using the DataTemplate as template for DataGridTemplateColumn.Header.
Create a custom data type that suits your purpose (with properties named ChannelDescription
and ChannelTag
in this example) and then bind the values to your 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>
It would be used like this:
In your view model, you would have a collection property, lets say called Items
:
public ObservableCollection<YourDataType> Items { get; set; }
(Your property should implement the INotifyPropertyChanged
interface unlike this one)
In your view, you would have a collection control, lets say a ListBox
:
<ListBox ItemsSource="{Binding Items}" ItemTemplate="{StaticResource myDataTemplate}" />
Then each item in the collection control will have the same DataTemplate
, but the values would come from the instances of type YourDataType
in the Items
collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.