I have one object DataSet which has a name property and a ID property. I have a list of datasets in my viewmodel, which should be the itemsource of a DataGrid Combobox column. I have defined the binding as follows:
dataGridControl:DataGridComboBoxColumn
Binding="{Binding DataSetIndex}"
Header="DataSet"
ItemsSource="{x:Bind Model.DataSets}"
DisplayMemberPath="Name"
Tag="DataSet" />
Now, this works, except for the fact that I somehow need to tell the binding that it should use the DataSet.ID property. So when a user selects a value in the combobox, the binding DataSetIndex should be set to a int, which is the DataSet.ID property. How can I do that in the binding? Right now I of course get an error saying that the itemsource does not have a int property, cause it tries to use the DataSet object as a whole. Now, is there no SelectedValuePath in the community toolkit? Do I have to use a templatecolumn?
Here is my updated question based on your solution. It also has the codebehind binding.
<dataGridControl:DataGridTemplateColumn Header="DataSet">
<dataGridControl:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate x:DataType="local:DataExtractionSetupViewModel">
<ComboBox x:Name="dataSetsComboBox" Loaded="ComboBox_Loaded"
DisplayMemberPath="Name"
SelectedValue="{Binding DataSetIndex, Mode=TwoWay}" SelectedValuePath="ID" IsDropDownOpen="True"/>
</DataTemplate>
</dataGridControl:DataGridTemplateColumn.CellEditingTemplate>
<dataGridControl:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DatasetIndex}"/>
</DataTemplate>
</dataGridControl:DataGridTemplateColumn.CellTemplate>
</dataGridControl:DataGridTemplateColumn>
Now my only question is, how can we make this custom template column look exactly like a normal datagrid combobox column, and also show the datasets name in the textbox instead of the index?
The following is using code-behind but works:
<toolkit:DataGridTemplateColumn>
<toolkit:DataGridTemplateColumn.CellTemplate>
<DataTemplate x:DataType="local:DataSet">
<ComboBox
DisplayMemberPath="Name"
Loaded="ComboBox_Loaded"
SelectedIndex="{x:Bind DataSetIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
if (sender is not ComboBox comboBox)
{
return;
}
comboBox.SetBinding(
ComboBox.ItemsSourceProperty,
new Binding()
{
Source = Model,
Path = new PropertyPath("DataSets"),
});
}
If you want to change how the ComboBox
looks, try setting:
CornerRadius
to 0BorderThickness
to 0Background
to Transparent