If I configure a new WPF application in Visual Studio 2010 and add the following + XAML code, data collection with collections inside will open. Now the problem is that changing the value through combobox does not apply to the associated data model. In other words: the MyValue property will never be set. It took me hours and I donβt know why this is not working. Also, many similar topics and suggestions were not.
Here is XAML. This is just a window with DataGrid enabled. There is a template column in the DataGrid where CellTemplate and CellEditingTemplate are installed. Both contain a ComboBox, which is populated with a list from the resource section. ComboBox.SelectedItem is bound to MyItem.MyValue:
<Window x:Class="DataGridComboBoxExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" xmlns:local="clr-namespace:DataGridComboBoxExample"> <Window.Resources> <local:MyItemList x:Key="ItemList"/> <DataTemplate x:Key="NotificationModeDataTemplate"> <ComboBox ItemsSource="{StaticResource ItemList}" SelectedItem="{Binding Path=MyValue, Mode=OneWay}" /> </DataTemplate> <DataTemplate x:Key="NotificationModeEditTemplate"> <ComboBox ItemsSource="{StaticResource ItemList}" SelectedItem="{Binding Path=MyValue, Mode=TwoWay}" /> </DataTemplate> </Window.Resources> <Grid> <DataGrid x:Name="myDataGrid" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTemplateColumn Header="Test" Width="100" CellTemplate="{StaticResource NotificationModeDataTemplate}" CellEditingTemplate="{StaticResource NotificationModeEditTemplate}" /> </DataGrid.Columns> </DataGrid> </Grid> </Window>
Here is the code. It contains the main ctor window, which simply sets the DataContext. MyItem is a data string that supports INotifyPropertyChanged. MyItemList is a list of options related to ComboBox.ItemsSource.
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); myDataGrid.ItemsSource = new List<MyItem> { new MyItem { MyValue = "i0" }, new MyItem { MyValue = "i1" }, new MyItem { MyValue = "i0" }, }; } } public class MyItem : INotifyPropertyChanged { public string MyValue { get { return myValue; } set { myValue = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("MyValue")); } } } private string myValue; public event PropertyChangedEventHandler PropertyChanged; } public class MyItemList : List<string> { public MyItemList() { Add("i0"); Add("i1"); Add("i2"); } }
source share