问题描述
|
如果我在Visual Studio 2010中设置了新的WPF应用程序并添加了以下代码+ XAML,则将打开一个数据网格,其中包含组合框。现在的问题是,通过组合框更改值不会传播到绑定数据模型。换句话说:永远不会设置名为MyValue的属性。现在花了我几个小时,我不知道为什么这行不通。也没有很多类似的线索和建议。
这里是XAML。它只是一个包含DataGrid的简单窗口。 DataGrid有一个模板列,其中设置了CellTemplate和CellEditingTemplate。两者都包含一个ComboBox,其中填充了资源部分中的列表。 ComboBox.SelectedItem绑定到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>
这里的代码。它包含仅设置DataContext的主Window ctor。 MyItem是支持INotifyPropertyChanged的行的数据模型。 MyItemList是绑定到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\"); }
}
解决方法
我怀疑您需要使SelectedItem绑定更新PropertyChanged上的源才能起作用。
SelectedItem = \“ {绑定路径=我的值,模式=双向,UpdateSourceTrigger =属性更改} \”
在调试时,我会让CellTemplate和CellEditingTemplate都引用您的编辑模板,以消除另一个无关的模板,直到您将其整理好为止。