[英]How to lose focus on DataGrid when clicking on another DataGrid?
I am using MVVM WPF and I need to lose focus, when I click on another DataGrid, so I will have selected only one row in one DataGrid. 我使用的是MVVM WPF,当我单击另一个DataGrid时,我需要失去焦点,因此在一个DataGrid中仅选择了一行。
Or if it is possible, to lose focus when I click outside of DataGrids? 或者,如果有可能,当我在DataGrids之外单击时会失去焦点? But will it lose focus also when I want to click edit button on selected row from DataGrid? 但是,当我想单击DataGrid中选定行的编辑按钮时,它也会失去焦点吗?
protected override void OnLostFocus(System.Windows.RoutedEventArgs e)
{
base.OnLostFocus(e);
this.SelectedItems.Clear();
this.SelectedItem = null;
}
This is my OnLostFocus, but I don't know how to catch the click in xaml (I am really new in xaml) 这是我的OnLostFocus,但我不知道如何在xaml中捕捉点击(我真的是xaml中的新手)
UPDATE: Can I use style trigger somehow to focus from one DataGrid to another? 更新:我可以使用样式触发器以某种方式将焦点从一个DataGrid集中到另一个吗?
try : 尝试:
datagrid1.UnselectAll();
datagrid2.Focus();
UPDATE : You can use MouseEnter event instead of override LostFocus like this: 更新:您可以使用MouseEnter事件,而不是像这样覆盖LostFocus:
private void dataGrid1_MouseEnter(object sender, MouseEventArgs e)
{
dataGrid2.UnselectAll();
}
private void dataGrid2_MouseEnter(object sender, MouseEventArgs e)
{
dataGrid1.UnselectAll();
}
XAML : XAML:
<DataGrid Focusable="True" Name="dataGrid1" MouseEnter="dataGrid1_MouseEnter" ItemsSource="{Binding}" SelectionUnit="Cell" CanUserDeleteRows="False" CanUserAddRows="False" CanUserReorderColumns="False" CanUserSortColumns="True" Margin="217,0,0,0" />
<DataGrid Focusable="True" Name="dataGrid2" MouseEnter="dataGrid2_MouseEnter" ItemsSource="{Binding}" SelectionUnit="Cell" CanUserDeleteRows="False" CanUserAddRows="False" CanUserReorderColumns="False" CanUserSortColumns="True" Margin="10,-10,343,10" />
I fixed it in code behind. 我在后面的代码中修复了它。 This works like a charm! 这就像一个魅力! (With MouseDown it didn't work well, I don't know why) (使用MouseDown效果不好,我不知道为什么)
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
dataGrid = GetTemplateChild("dataGrid") as DataGrid;
dataGrid.MouseUp += new MouseButtonEventHandler(dataGrid_MouseUp);
docGrid = GetTemplateChild("docGrid") as DataGrid;
docGrid.MouseUp += new MouseButtonEventHandler(docGrid_MouseUp);
}
public void dataGrid_MouseUp(object sender, MouseEventArgs e)
{
docGrid.UnselectAll();
}
public void docGrid_MouseUp(object sender, MouseEventArgs e)
{
dataGrid.UnselectAll();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.