我有以下带有附加行为的 UserControl。目前,我必须选择其中一项 DataGrid 项目才能运行该行为。
只是在这里猜测,但这是可以理解的,因为这些容器不可聚焦或不应该注册键盘事件,所以它会转到下一个可用的孩子???
我可以将此功能放在窗口上,但是此 UserControl 可以与另一个 UserControl 交换,我更喜欢它不要躺在那里。这只是我的应用程序中的一个独特情况,其中窗口上唯一的东西是 DataGrid,我不一定要选择 DataGrid 项来开始该行为。
我的问题是:是否有可能使以下行为起作用?在 UserControl、Grid 或其他一些允许这样做的控件上。
<UserControl x:Class="UserManagement.LaunchPad"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:helpers="clr-namespace:UserManagement.Helpers"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<i:Interaction.Behaviors>
<helpers:OpenPopupBehaviors FindPopupObject="{Binding ElementName=PopupFind}"
GotoPopupObject="{Binding ElementName=PopupGoto}" />
</i:Interaction.Behaviors>
<Grid>
<DockPanel>
<DataGrid />
</DockPanel>
<Popup Name="PopupGoto" />
<Popup Name="PopupFilter "/>
</Grid>
</UserControl>
这是行为:
class OpenPopupBehaviors : Behavior<UserControl>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.KeyDown += _KeyBoardBehaviorKeyDown;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.KeyDown -= _KeyBoardBehaviorKeyDown;
}
void _KeyBoardBehaviorKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.F && (Keyboard.Modifiers & (ModifierKeys.Control)) == (ModifierKeys.Control))
{
var popup = FindPopupObject as UserManagement.Controls.NonTopmostPopup;
if (popup == null)
return;
popup.IsOpen = true;
}
if (e.Key == Key.G && (Keyboard.Modifiers & (ModifierKeys.Control)) == (ModifierKeys.Control))
{
var popup = GotoPopupObject as Popup;
if (popup == null)
return;
popup.IsOpen = true;
}
}
public static readonly DependencyProperty FindPopupObjectProperty =
DependencyProperty.RegisterAttached("FindPopupObject", typeof(object), typeof(OpenPopupBehaviors), new UIPropertyMetadata(null));
public object FindPopupObject
{
get { return (object)GetValue(FindPopupObjectProperty); }
set { SetValue(FindPopupObjectProperty, value); }
}
public static readonly DependencyProperty GotoPopupObjectProperty =
DependencyProperty.RegisterAttached("GotoPopupObject", typeof(object), typeof(OpenPopupBehaviors), new UIPropertyMetadata(null));
public object GotoPopupObject
{
get { return (object)GetValue(GotoPopupObjectProperty); }
set { SetValue(GotoPopupObjectProperty, value); }
}
}