Dot-Net
DataGrid 數據綁定/更新中的 WPF 組合框不起作用
如果我在 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="{綁定路徑=MyValue,模式=TwoWay,UpdateSourceTrigger=PropertyChanged }"
我會讓 CellTemplate 和 CellEditingTemplate 在調試時都引用你的編輯模板,以消除另一個不相關的模板,直到你把它整理好。