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

前提是你 提交于 2019-12-23 08:30:09

问题


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?


回答1:


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

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

}



回答2:


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

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



回答3:


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

1) first trigger : when you selected a new item

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

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

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 !



来源:https://stackoverflow.com/questions/19322271/wpf-datagrid-combobox-column-how-to-manage-event-of-selection-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!