简体   繁体   中英

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

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?

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;

}

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;

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM