我有以下具有附加行爲的UserControl。此刻,我必須選擇其中一個DataGrid項目才能運行該行爲。如何在UserControl上實現交互行爲
只能在這裏猜測,但它是可以理解的,因爲這些容器不可聚焦或不應該註冊鍵盤事件,所以它會去下一個孩子?
我可以把這個功能放在窗口上,但是這個UserControl可以與另一個UserControl交換出去,我更喜歡它不會躺在身邊。 這只是我的應用程序中唯一的情況,窗口中唯一的東西是DataGrid,我不一定要選擇DataGrid項目來開始行爲。
我的問題是:是否有可能得到以下行爲工作?無論是在用戶控件,網格或可能允許這一點的其他控制。
<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); }
}
}
我還添加了可調焦=「true」添加到用戶控件,看看是否發揮了作用。不幸的是,當屏幕第一次加載時,我按下Ctrl + f沒有任何反應,但是當我選擇一個項目時,它會打開Popup。 – Hank
焦點只是讓它可以專注。你可以做的是在主窗口的'LaunchPad'的元素中設置'FocusManager.FocusedElement =「{Binding RelativeSource = {RelativeSource Self}}」''。這將有助於你集中控制。如果仍然不起作用,則將事件附加到父窗口而不是用戶控件。 – pushpraj