简体   繁体   中英

The SelectedItem of DataGrid in WPF does not fire if I switch from one ComboBox with IsEditable="True" to another

In WPF I have a DataGrid . I am using MVVM.

    <DataGrid x:Name="dataGrid" ItemsSource="{Binding DisplayedRows}" 
              SelectedItem="{Binding SelectedRow}" SelectionUnit="FullRow">

If I change row then the setter of the SelectedRow runs as it should.

There is one exception. One of the columns is a DataGridTemplateColumn which contains ComboBox with IsEditable="True"

    <DataTemplate x:Key="CategoryEditingTemplate">
        <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, 
            AncestorType={x:Type DataGrid}}, Path=DataContext.AppData.CategoryObjects}" 
                  SelectedItem="{Binding Category, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" 
                  DisplayMemberPath="FullName" IsEditable="True">
        </ComboBox>
    </DataTemplate>

If I start to edit the content of the ComboBox then I click to another editable ComboBox in another row then the setter of the SelectedRow does not run. I can edit the content of the second ComboBox with keyboard. If I click to another cell in the same row then the system realizes that the row has changed and the setter starts. I want the setter to run as soon as I leave a row.

Update 1

Editing mode of a ComboBox in a DataGrid 在此处输入图像描述

The input control ( ComboBox ) steals the focus which prevents the DataGrid control from actually selecting the row.

You could handle the PreviewMouseLeftButtonDown event for the input control to overcome this:

private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) =>
    dataGrid.SelectedItem = ((ComboBox)sender).DataContext;

XAML:

<DataTemplate x:Key="CategoryEditingTemplate">
    <ComboBox PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown" ItemsSource ...

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