I have a class derived from DataGrid which works very nicely when all the columns are DataGridTextColumns and allows me to extract the distinct strings in each column. However, I've had to expand it to allow DataGridComboBox columns and I can't find a way to get those strings.
If I have a DataGridTextColumn I can use the following code to get a sorted list of distinct values as strings. This code is in my subclassed DataGrid and it doesn't need to know the data source or the data source type at runtime.
var type = this.Items[0].GetType();
var propertyInfo = type.GetProperty(columnName);
// Sorts the Items in the natural order for the property/column used
// then gets just that property as strings
// distinct etc.
List<string> query = this.Items.Cast<object>()
.OrderBy(i => propertyInfo.GetValue(i))
.Select(i => $"{propertyInfo.GetValue(i)}")
.Distinct()
.ToList();
return query;
The DataGridComboBoxColumn is linked to my object's SupplierId and I can't find a way of converting the SupplierId to a supplier Name. Here is the XAML for the column definition.
<DataGridComboBoxColumn
Header="Supplier"
SelectedValueBinding="{Binding SupplierId, Mode=TwoWay}"
DisplayMemberPath="Name"
SelectedValuePath="Id">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.SuppliersList, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.SuppliersList, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
public class MyObject
{
public int SupplierId { get; set; }
// other properties
}
public class Supplier
{
public int Id { get; set; }
public string Name { get; set; }
}
I've come to the point where I don't think it can be done and I'm going to have to redesign my DataGrid class but I'd really rather not.