【问题标题】:WPF Datagrid Items Refresh lose focusWPF Datagrid Items Refresh失去焦点
【发布时间】:2013-04-03 08:16:37
【问题描述】:

当我的 observableCollection 在视图模型中更新时刷新我的数据网格是一场噩梦。在我发现 DataGrid 不会响应 ObservableCollection 引发的事件后,我发现了 DataGrid.Items.Refresh。 它确实刷新,但随后 DataGrid 失去焦点。我有一个简单的列表,我想在按下一个键然后更新时更改一个值。用户在使用键盘快捷键时必须再次选择鼠标,这是不可接受的...... 这是一个简单的例子:

            <DataGrid x:Name="MyDataGrid" SelectionMode="Single" AutoGenerateColumns="False" IsReadOnly="True" KeyUp="MyDataGrid_KeyUp">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name" Binding="{Binding Path=First}"/>
                    <DataGridTextColumn Header="Last Name" Binding="{Binding Path=Last}"/>
                </DataGrid.Columns>
            </DataGrid>

以及背后的代码:

    private void MyDataGrid_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key.Equals(Key.Space))
        {
            MyDataGrid.Items.Refresh();
        }
    }

附言在这个例子中,我在后面的代码中设置了 ItemsSource,而不是绑定到 ObservableCollection。另外我只使用代码隐藏而不是 ViewModel,但问题是一样的。

编辑:最初的问题是我没有在课堂上使用 NotifyPropertyChanged。但是,这里提出的问题仍然是“开放的”,我在执行 Refresh() 时无法真正理解失去焦点的问题

【问题讨论】:

    标签: wpf datagrid focus refresh


    【解决方案1】:

    当我的 observableCollection 在视图模型中更新时刷新我的数据网格是一场噩梦。 - 为什么这是一场噩梦?不过应该很容易。

    关于您的问题。请尝试以下方法

    private void MyDataGrid_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key.Equals(Key.Space))
        {
            MyDataGrid.Items.Refresh();
            MyDataGrid.Focus();
        }
    }
    

    您可以找到相关文档here

    编辑
    让我们试试这个

    private void MyDataGrid_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key.Equals(Key.Space))
        {
            MyDataGrid.Items.Refresh();
            FocusManager.SetFocusedElement(MyDataGrid);
        }
    }
    

    更多信息请关注here

    【讨论】:

    • 我不记得说我试过了,但它失败了。它返回 true 但行为完全相同。
    • Yes. This is the answer。我有reproduced 的问题。当我使用后面的代码时,我使用Focus() 方法实现了这一点。然后我尝试使用它without code behind 文件(在我的view model 中)。我试图绑定DataGrid 控件的Focusable 属性。但它没有用。你有什么想法吗?
    • 感谢再次尝试 DHN 但不幸的是 ItemCollection 不包含 Focus() 方法:(
    • @Haritha 不,我不知道。但是绑定Focusable一定会失败,因为它并没有设置焦点,而是指示一个控件是否可以被聚焦。请查看here 了解更多信息。
    • @Louro 最后一次尝试,在此之后我只能建议您定期从FocusManager 中读取焦点元素以获取线索,哪个元素获得焦点。也许它会给你一个想法,为什么会这样。
    【解决方案2】:

    通过调度程序安排刷新对我有用(使用 TreeView)。

    所以不要这样做(失去焦点):

    tree.Items.Refresh();
    

    我这样做(不会失去焦点):

    Dispatcher.BeginInvoke(new Action(() => tree.Items.Refresh()));
    

    不知道为什么,但它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-05
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多