DataGridComboBoxColumn操作处理程序
本文关键字:程序 处理 操作 DataGridComboBoxColumn | 更新日期: 2023-09-27 18:25:07
我有一个包含动态创建的DataGridComboBoxColumn的WPF,它有一个组合框,我可以更改任何行中的值。该表在另一列中也包含一个复选框,如果我更改此复选框,它会在每次更改行时调用一个方法,当我更改组合框中的值时,我希望得到相同的结果
我有一个Rum对象的列表,为此目的有三种方法
public int rumStyle { get; set; }
public string rumStyleDesc { get; set; } // string representation of ruymStyle
public bool rumIsValid { get; set; }
此复选框部分适用于
DataGridTemplateColumn textColumnValid = new DataGridTemplateColumn();
textColumnValid.Header = headerRumIsValid;
FrameworkElementFactory checkBoxFactory = new FrameworkElementFactory(typeof(CheckBox));
Binding rumIsValidBinding = new Binding("rumIsValid");
checkBoxFactory.SetValue(CheckBox.IsCheckedProperty, rumIsValidBinding);
checkBoxFactory.AddHandler(CheckBox.ClickEvent, new RoutedEventHandler(LostFocus));
DataTemplate rumIsdValidTemplate = new DataTemplate();
rumIsdValidTemplate.VisualTree = checkBoxFactory;
textColumnValid.CellTemplate = rumIsdValidTemplate;
_dgData.Columns.Add(textColumnValid);
这部分确实在每行显示一个组合框,但我希望它在选择更改时调用LostFocus(或其他方法)。
DataGridComboBoxColumn comb = new DataGridComboBoxColumn();
comb.Header = headerRumStyle;
comb.SelectedValueBinding = new Binding("rumStyleDesc");
comb.ItemsSource = _rumStyles.getRumStyleNames();
FrameworkElementFactory comboFactory = new FrameworkElementFactory(typeof(ComboBoxItem));
comboFactory.SetValue(ComboBox.SelectedItemProperty, new Binding("rumStyleDesc"));
comboFactory.AddHandler(ComboBox.SelectionChangedEvent,
new SelectionChangedEventHandler(comboBox1_SelectionChanged));
DataTemplate comboboxTemplate = new DataTemplate();
comboboxTemplate.VisualTree = buttonFactory;
// How do I do this part
// comb.CellTemplate = comboboxTemplate;
_dgData.Columns.Add(comb);
第二个但不太重要的问题是,我可以在组合框中显示rumStlyeDsc,但以某种方式读回rumstyleId吗。
最终找到了如何做到这一点。
首先,我把RumStyles的列表添加到我的每个朗姆酒中,并用一种方法将风格名称作为列表
public RumStyles rumStyles { get; set; }
public List<string> rumStlyesList{ get {return rumStyles.getRumStyleNames();}}
然后我想出了以下代码来在DataGridTemplateColumn而不是DataGridComboBoxColumn 中构建ComboBox
DataGridTemplateColumn changeRumStyleColumn = new DataGridTemplateColumn();
changeRumStyleColumn.Header = headerRumStyle;
FrameworkElementFactory styleComboFactory =
new FrameworkElementFactory(typeof(ComboBox));
Binding selectedStyle = new Binding("rumStyleDesc");
styleComboFactory.SetBinding(ComboBox.ItemsSourceProperty,
new Binding("rumStlyesList"));
styleComboFactory.SetBinding(ComboBox.SelectedItemProperty, new Binding("rumStyleDesc"));
styleComboFactory.SetValue(ComboBox.SelectedItemProperty, selectedStyle);
styleComboFactory.AddHandler(ComboBox.SelectionChangedEvent,
new SelectionChangedEventHandler(comboBox1_SelectionChanged));
DataTemplate rumStyleTemplate = new DataTemplate();
rumStyleTemplate.VisualTree = styleComboFactory;
changeRumStyleColumn.CellTemplate = rumStyleTemplate;
_dgData.Columns.Add(changeRumStyleColumn);
还有一个问题,可以通过更改SelectionChangedEvent来解决,即当首次显示行时,调用comboBox1_SelectionChanged。