【问题标题】:The SelectedItem of DataGrid in WPF does not fire if I switch from one ComboBox with IsEditable="True" to another如果我从一个 IsEditable="True" 的 ComboBox 切换到另一个 ComboBox,WPF 中 DataGrid 的 SelectedItem 不会触发
【发布时间】:2021-11-25 21:55:24
【问题描述】:

在 WPF 中,我有一个 DataGrid。我正在使用 MVVM。

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

如果我更改行,则 SelectedRow 的设置器将按应有的方式运行。

有一个例外。 其中一列是DataGridTemplateColumn,其中包含ComboBoxIsEditable="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>

如果我开始编辑ComboBox 的内容,然后单击另一行中的另一个可编辑ComboBox,则SelectedRow 的设置器不会运行。我可以用键盘编辑第二个ComboBox 的内容。如果我单击同一行中的另一个单元格,则系统会意识到该行已更改并且设置器启动。我希望设置器在我离开一行后立即运行。

更新 1

ComboBoxDataGrid 中的编辑模式

【问题讨论】:

    标签: wpf mvvm combobox selecteditem


    【解决方案1】:

    输入控件 (ComboBox) 窃取焦点,阻止 DataGrid 控件实际选择行。

    您可以为输入控件处理PreviewMouseLeftButtonDown 事件来克服这个问题:

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

    XAML:

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

    【讨论】:

    • 谢谢@mm8 我尝试了你的建议。如果我单击 ComboBox 的文本,则该函数不会运行。我直接进入编辑模式,我仍然可以点击另一个ComboBox的文本。
    • 直接进入编辑模式?那是什么意思? CellTemplate 中是否也有 ComboBox?然后你还需要处理这个PreviewMouseLeftButtonDown
    • 嗨@mm8,在编辑模式下,我的意思是当我点击ComboBox 并选择其内容时,我可以用键盘更改文本(我在问题中添加了图像)。目前我对CellTemplateCellEditingTemplate 使用相同的˙DataTemplate`。如果我将PreviewMouseLeftButtonDown 添加到DataGrid 本身,那么有趣的是,这个事件应该会触发。
    • 点击ComboBox时触发。
    • OnPreviewMouseLeftButtonDown 应该在我单击ComboBox 时触发,但它没有触发,而是ComboBox 进入编辑模式。如果我现在再次选择相同的ComboBox,那么OnPreviewMouseLeftButtonDown 就会触发。 (很奇怪)
    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2014-07-29
    • 2020-01-13
    • 2014-05-30
    • 2019-07-09
    • 2014-10-10
    相关资源
    最近更新 更多