【问题标题】:DataGrid LostFocus Event Raised when User Changes Row用户更改行时引发 DataGrid LostFocus 事件
【发布时间】:2016-02-23 16:14:48
【问题描述】:

这是用于创建数据网格的 XAML:

<DataGrid
            x:Name="dgrComments"
            Height="200">
            <DataGrid.Columns>
            <DataGridTextColumn
                Binding="{Binding Path=RepairID}"
                Visibility="Hidden" />
            <DataGridTextColumn
                Binding="{Binding Path=Sequence}"
                Visibility="Hidden" />
            <DataGridTextColumn
                Binding="{Binding Path=Entry}"
                DisplayIndex="0" />
            <DataGridTextColumn
                Binding="{Binding Path=LastUpdate}"
                Visibility="Hidden" />
        </DataGrid.Columns>
    </DataGrid>

这是我将数据绑定到网格的方式(“Sequence”是 RepairComments 表中的一列):

RepairFilter=<a text string that is a valid filter>
dvComments = New DataView(dsPIM.Tables("RepairDetails"), RepairFilter, "Sequence", DataViewRowState.CurrentRows)
dgrComments.ItemsSource = dvComments

这一切都很好,除了当用户更改所选行时 datagrid dgrComments.LostFocus 事件被触发。为什么?

【问题讨论】:

    标签: wpf vb.net datagrid


    【解决方案1】:

    DataGrid.LostFocus 的问题是每次编辑单元格都会触发它。

    这并不总是一件坏事,因为处理单元更新或注册单元更改很有用。

    但是,如果您想检测用户何时将 DataGrid 整体离开到页面上其他地方的另一个控件,这很烦人。

    解决方案是检测现在的焦点到底是什么,并确定它是在 DataGrid 内部还是外部。

    为此,我们可以使用 FocusManager 来获取当前聚焦的元素。 然后我们只需检查父容器是否是 DataGrid 的一部分。

    如果不是,我们知道它在 DataGrid 之外,这表示我们的 DataGrid.LostFocus 事件。

    private void dgrComments_LostFocus(object sender, RoutedEventArgs e) 
    { 
        Control ctrl = FocusManager.GetFocusedElement(this) as Control;  
        if (ctrl.Parent != null && ctrl.Parent.GetType() != typeof(DataGridCell)) 
            MessageBox.Show("outside!"); 
    }
    

    改编自code.msdn.com

    【讨论】:

    • 实际上,即使没有进行任何编辑,也会触发 LostFocus 事件。只需更改选定的单元格即可触发该事件。太糟糕了,文档中没有提到。
    • 正确!如果能解决您的问题,请将我的回答标记为正确。
    【解决方案2】:

    如果你有 CollectionViewSource 属性,最好的解决方案

        private CollectionViewSource epairDetailsViewSource;
    
        private void FormItems_Loaded(object sender, RoutedEventArgs e)
        {
            repairDetailsViewSource= ((CollectionViewSource)this.FindResource("repairDetailsViewSource"));
    
            context = new MyDbContext();
            context.RepairDetails.Load();
    
            repairDetailsViewSource.Source = context.Items.Local;
    
            repairDetailsViewSource.View.CurrentChanging += View_CurrentChanging;
        }
    
        private void View_CurrentChanging(object sender, CurrentChangingEventArgs e)
        {
            ((RepairDetails)repairDetailsViewSource.View.CurrentItem).//...
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      相关资源
      最近更新 更多