Reputation:
if I have DataGridComboBoxColumn in XAML
<DataGridComboBoxColumn Header="Department Id" x:Name="comboboxColumn1"
I can refer to the comboboxColumn1.Itemsource in code using
comboboxColumn1.ItemsSource = comboboxSource;
If I now use DataGridTemplateColumn instead...
<DataGridTemplateColumn x:Name="Col2" Header="name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="Combobox2" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
how do I then set the Combobox2.ItemSource in code?
Upvotes: 0
Views: 592
Reputation: 132568
Does it have to be in code behind??
You are building a DataTemplate
, which is the template used anytime WPF needs to render that specific DataGridCell. Therefore, there is never a single instance of your ComboBox, but rather as many instances as you have DataGridCells being displayed (which is why you can't actually reference the item by Name).
If I had to set the ItemsSource
in code-behind, I would just put a Loaded
event on the ComboBox and set it there.
Or if the ItemsSource
is not static, then you can use the ItemContainerGenerator to get the template for a specific DataGrid item, and find it through that.
But really you should set the ItemsSource
in the XAML using a StaticResource
, or a binding if you can, so I'd suggest figuring out how to set the binding through the XAML using a RelativeSource
or ElementName
binding to find whatever object contains your ItemsSource
first, and only settling for using code-behind if you absolutely have to.
Also, the reason why comboboxColumn1.ItemsSource = comboboxSource;
works is because you're setting DataGridComboBoxColumn.ItemsSource
, not ComboBox.ItemsSource
, and there's only a single object named comboboxColumn1
Upvotes: 2