如何为datagrid组合框的selectionchanged设置事件?

时间:2018-05-29 08:45:01

标签: wpf combobox datagrid eventsetter

您好我有一个wpf项目,它将datagrid绑定到模块,如下所示:

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

这很好用。现在我想添加一些功能,包括设置组合框SelectionChanged的事件。所以我改变了xaml这样的文件:

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

在后端添加一个函数,如下所示:

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

但是当我更改组合框单元格时,这会使项目按error: "The Application is in break mode."细分。那可能是什么问题呢?提前谢谢!

2 个答案:

答案 0 :(得分:0)

像我一样愚蠢。只需在combobox内设置事件即可解决问题。

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

答案 1 :(得分:0)

您需要将Style的{​​{1}}属性设置为ComboBox

Style

或者您可以直接在<DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding Values}" SelectedItem="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> <ComboBox.Style> <Style TargetType="{x:Type ComboBox}"> <EventSetter Event="SelectionChanged" Handler="ValueChanged" /> </Style> </ComboBox.Style> </ComboBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> 元素上挂接事件处理程序并删除ComboBox

Style