I have a DataGrid that has two columns (A and B). Each column cell contains a combo box control.
I have an object that contains two list items that I want to bind to the grid view, but the binding does not work.
Binding in both DataTemplates not working correctly. UI shows the namespace instead of value.
Sample Project: https://1drv.ms/u/s!Ah27QQNpKj4jj2xsIsQamaOXOlin?e=jNAj2H
ViewModel
public class MainWindowViewModel {
public List < MainObject > MainObjects { get; set; }
public MainWindowViewModel() {
MainObjects = new List < MainObject > {
new MainObject {
AColumns = new List < ColumnA > {
new ColumnA { Name = "A1" },
new ColumnA { Name = "A1" }
},
BColumns = new List < ColumnB > {
new ColumnB { Name = "B1" },
new ColumnB { Name = "B1" }
},
}
};
}
}
public class MainObject {
public List < ColumnA > ?AColumns { get; set; }
public List < ColumnB > ?BColumns { get; set; }
}
public class ColumnA {
public string ? Name { get; set; }
}
View:
<Window x:Class="TestDataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<DataGrid ItemsSource="{Binding MainObjects}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Column A" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Center">
<TextBlock.Text>
<PriorityBinding>
<Binding Path="Name" Mode="TwoWay" />
</PriorityBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox IsEditable="True" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding AColumns}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
CodePudding user response:
You have to use the "DisplayMemberPath" property instead of the "Text" property. like this
<ComboBox IsEditable="True" ItemsSource="{Binding AColumns}" SelectedValuePath="Name" DisplayMemberPath="Name"/>