Search code examples
wpfcomboboxdatagrideventsetter

How to set event for selectionchanged of datagrid combobox?


Hi I have a wpf project which binding datagrid to module like this:

<DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>
        <DataGridTemplateColumn Header="Values">
           <DataGridTemplateColumn.CellTemplate>
              <DataTemplate>
                <ComboBox ItemsSource="{Binding Values}" SelectedItem="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
              </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

This works fine. Now I want to add some features including setting an event the combobox SelectionChanged. So I changed the xaml file like this:

<DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>
        <DataGridTemplateColumn Header="Values">
           <DataGridTemplateColumn.CellTemplate>
              <DataTemplate>
                <ComboBox ItemsSource="{Binding Values}" SelectedItem="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                    /!-- Add an EventSetter here. -->
                    <Style TargetType="{x:Type ComboBox}">                                                                                           
                         <EventSetter Event="SelectionChanged" Handler="ValueChanged" />                                                                                  
                    </Style>
                </ComboBox>
              </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

And add an function in the back end like this:

    private void ValueChanged(object sender, SelectionChangedEventArgs e)
    {
         var comboBox = sender as ComboBox;
         if (comboBox.SelectedItem != null)
         {
              //do something here.
         }
    }

But this makes the project breakdown with error: "The Application is in break mode." when I changed the combobox cell. So what could be the problem? Thanks in advance!


Solution

  • Stupid as i am. Just setting the event inside the combobox fix the problem.

    <DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>
        <DataGridTemplateColumn Header="Values">
           <DataGridTemplateColumn.CellTemplate>
              <DataTemplate>
                <ComboBox ItemsSource="{Binding Values}" SelectedItem="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                         SelectionChanged="ValueChanged" />
              </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>