WPF 数据网格组合框可编辑
本文关键字:编辑 组合 网格 数据 数据网 WPF | 更新日期: 2023-09-27 18:36:53
我的目标是在DataGrid
中放置一个可编辑的ComboBox
,为此我在CellTemplate
中放置了一个TextBlock
,在CellEditingTemplate
中放置了一个ComboBox
。但是如何将我的TextBlock
与ComboBox
中所选项目的文本绑定?
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetBinding(TextBlock.TextProperty, new Binding("Description"));
dgc.ClipboardContentBinding = new Binding("Description");
var template = new DataTemplate();
template.VisualTree = textBlockFactory;
dgc.CellTemplate = template;
var comboBoxFactory = new FrameworkElementFactory(typeof(ComboBox));
template = new DataTemplate();
template.VisualTree = comboBoxFactory;
Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(UserControl), 1);
b.Path = new PropertyPath(BindingList);
comboBoxFactory.SetBinding(ComboBox.ItemsSourceProperty, b);
comboBoxFactory.SetValue(ComboBox.IsEditableProperty, true);
comboBoxFactory.SetValue(ComboBox.SelectedValueProperty, new Binding("Type"));
comboBoxFactory.SetValue(ComboBox.SelectedValuePathProperty, "Id");
comboBoxFactory.SetValue(ComboBox.DisplayMemberPathProperty, "Description");
dgc.CellEditingTemplate = template;
dgc.SortMemberPath = BindingCurrentItem;
在此特定方案中,您必须在支持 DataGridItem 的模型中再创建一个属性说 SelectedBinding。属性的类型应为绑定列表中的项类型。
然后,您可以将组合框的选定项绑定到它作为
comboBoxFactory.SetValue(ComboBox.SelectedItemProperty, new Binding("SelectedBinding"));
并且您可以将文本块绑定更新为
dgc.ClipboardContentBinding = new Binding("SelectedBinding.Description");