I am currently working a a WPF project with MVVM.
I have a DataGrid
bound to an ObservableCollection
of Models like this:
class Model : INotifyPropertyChanged
{
private string m_Name;
public string Name
{
get
{
return m_Name;
}
set
{
m_Name = value;
OnPropertyChanged("Name");
}
}
private List<string> m_Names;
public List<string> Names
{
get
{
return m_Names;
}
set
{
m_Names = value;
OnPropertyChanged("Names");
}
}
private double? m_Value;
public double? Value
{
get
{
return m_Value;
}
set
{
m_Value = value;
OnPropertyChanged("Value");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Now I'd like to use a DataGridComboBoxColumn
to have a Combobox with my Property "Name" as the SelectedItem and Names as the ItemSource.
Each of my Models has it's own set of names, which aren't identical with the name of any of the other models.
I've googeled and looked through StackOverflow, but I didn't find any solution. I've also tried to aplly filters like i know DevExpress Grid Controls can do, but I didn't find anything for basic WPF DataGrids.
How can I bind my DataGridComboBoxColumn
to a Property List
in my Model?
If you use DataGridComboBoxColumn you have to feed ItemsSource with a static resource, this is stated in the "Remarks" section https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.datagridcomboboxcolumn?view=netframework-4.8
Because you have different "Names" for each view model you can use DataGridTemplateColumn instead of DataGridComboBoxColumn
<DataGridTemplateColumn Header="Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Names}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>