DataGridComboBoxColumn ActionHandler

时间:2012-02-20 15:30:30

标签: c# wpf datagrid

我有一个包含动态创建的DataGridComboBoxColumn的WPF,它有一个comboBox,我可以更改任何行中的值。该表还包含另一列中的复选框,如果我更改它,每次更改行时都调用一个方法,当我更改组合框中的值时我想要相同的结果

我有一个我的朗姆酒对象列表,为此目的有三个方法

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);

第二个但不太重要的问题是我可以在组合框中显示rumStlyeDesc但是以某种方式回读了rumstyleId。

1 个答案:

答案 0 :(得分:1)

最终找到了怎么做。

首先,我将RumStyles列表添加到我的每个朗姆酒中,并使用一种方法将样式名称作为List

public RumStyles rumStyles { get; set; }
public List<string> rumStlyesList{ get {return rumStyles.getRumStyleNames();}}

然后我想出了以下代码来构建DataGridTemplateColumn中的ComboBox而不是DataGridComboBoxColumn

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。