Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
FrancescoDS Avatar asked Oct 11 '13 15:10

FrancescoDS


3 Answers

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;

}
like image 155
kevinpo Avatar answered Nov 11 '22 23:11

kevinpo


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;
like image 42
Kaloyan Penov Avatar answered Nov 11 '22 23:11

Kaloyan Penov


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 !

like image 3
Mr Rubix Avatar answered Nov 12 '22 01:11

Mr Rubix