Reputation: 995
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?
Upvotes: 12
Views: 21658
Reputation: 57
The problem of getting SelectionChanged events to fire on DataGridComboBoxColumn cells was one that plagued me recently. I used the following solution:
private void DataGridView_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
if (e.Column.DisplayIndex == 3) //Use this IF statement to specifiy which combobox columns you want to attach the event to.
{
ComboBox? cb = e.EditingElement as ComboBox;
if (cb != null)
{
// As this event fires everytime the user starts editing the cell you need to dettach any previously attached instances of "My_SelectionChanged", otherwise you'll have it firing multiple times.
cb.SelectionChanged -= My_SelectionChanged;
// now re-attach the event handler.
cb.SelectionChanged += My_SelectionChanged;
}
}
}
Then set up your custom SelectionChanged event handler to whatever you need:
private void My_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Your event code here...
}
Upvotes: 2
Reputation: 1519
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 !
Upvotes: 5
Reputation: 81
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;
Upvotes: 6
Reputation: 1963
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;
}
Upvotes: 22