WPF 数据网格组合框列:如何管理选择更改的事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19322271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:49:58  来源:igfitidea点击:

WPF datagrid combobox column: how to manage event of selection changed?

c#wpfdatagridcombobox

提问by FrancescoDS

I have a datagrid, with a combobox column

我有一个数据网格,带有一个组合框列

<DataGridComboBoxColumn x:Name="DataGridComboBoxColumnBracketType" Width="70" Header="Tipo di staffa" SelectedValueBinding="{Binding type, UpdateSourceTrigger=PropertyChanged}">                    
            </DataGridComboBoxColumn>

I want an event that is fired only when the user changes the value into the combobox. How can I resolve this?

我想要一个仅当用户将值更改为组合框时才会触发的事件。我该如何解决这个问题?

回答by kevinpo

I found a solution to this on CodePlex. Here it is, with some modifications:

我在CodePlex上找到了解决方案。这是,经过一些修改:

<DataGridComboBoxColumn x:Name="Whatever">                    
     <DataGridComboBoxColumn.EditingElementStyle>
          <Style TargetType="{x:Type ComboBox}">
               <EventSetter Event="SelectionChanged" Handler="SomeSelectionChanged" />
          </Style>
     </DataGridComboBoxColumn.EditingElementStyle>           
</DataGridComboBoxColumn>

and in the code-behind:

并在代码隐藏中:

private void SomeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
     var comboBox = sender as ComboBox;
     var selectedItem = this.GridName.CurrentItem;

}

回答by Kaloyan Penov

And the xaml code provided by @kevinpo from CodePlex and help from David Mohundro's blog, programatically:

以及 CodePlex 的 @kevinpo 提供的 xaml 代码和David Mohundro 博客的帮助,以编程方式:

var style = new Style(typeof(ComboBox));
style.Setters.Add(new EventSetter(ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(SomeSelectionChanged)));
dataGridComboBoxColumn.EditingElementStyle = style;

回答by Mr Rubix

To Complete Kevinpo answer, for the code behind you should add some protection because the selectionChanged event is triggered 2 time with a datagridcolumncombobox:

要完成 Kevinpo 的回答,您应该为后面的代码添加一些保护,因为 selectionChanged 事件是使用 datagridcolumncombobox 触发的 2 次:

1) first trigger : when you selected a new item

1)第一次触发:当你选择一个新项目时

2) Second trigger : when you click on an other datagridcolumn after you selected a new item

2)第二次触发:当您选择一个新项目后单击另一个数据网格列时

The problem is that on the second trigger the ComboBox value is null because you don't have changed the selected item.

问题是在第二个触发器上,ComboBox 值为空,因为您没有更改所选项目。

private void SomeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var comboBox = sender as ComboBox;
    if (comboBox.SelectedItem != null)
    {
        YOUR CODE HERE
    }
}

That was my problem, I wish it will help someone else !

那是我的问题,我希望它能帮助别人!