0

I noticed that KeyTrigger does not fire when used inside a Popup control.

<UserControl x:Class="SilverlightBindingTest.iTest"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="400"
         xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
         xmlns:ii="clr-namespace:Microsoft.Expression.Interactivity.Input;assembly=Microsoft.Expression.Interactions"
         xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions">

    <Grid x:Name="LayoutRoot" Background="White">
        <Popup IsOpen="True">
            <i:Interaction.Triggers>
                <ii:KeyTrigger Key="Enter">
                    <ei:ChangePropertyAction TargetName="alert" PropertyName="Visibility" Value="Visible" />
                </ii:KeyTrigger>
            </i:Interaction.Triggers>

            <StackPanel>
                <TextBox />
                <TextBlock Text="hi" x:Name="alert" Visibility="Collapsed"/>
            </StackPanel>
        </Popup>
    </Grid>
</UserControl>

When you remove the Popup part, this works as expected ("hi" appears when you press Enter).

What's going on here? I can't think of a reason why KeyTrigger should be failing.

4

1 回答 1

0

这里发生了什么?

也许KeyTrigger代码在应用程序根目录上添加了监听器,在这种情况下,它永远不会从 Popup 控件中冒出来(因为它不在可视树中)。好吧,没问题,我会检查来源,然后……哦等等,来源是秘密和专有的。感谢微软!

无论如何,这里有一个键触发器,它将侦听器附加到 TriggerBase.AssociatedObject,以便它可以在弹出窗口中工作。

public class KeyTriggerThatWorks : TriggerBase<FrameworkElement>
{
    private FrameworkElement _target;

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += (sender, args) =>
        {
            _target = AssociatedObject;
            _target.KeyDown += new KeyEventHandler(Visual_KeyDown);
        };  
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        _target.KeyDown -= new KeyEventHandler(Visual_KeyDown);   
    }

    public Key Key { get; set; }

    void Visual_KeyDown(object sender, KeyEventArgs args)
    {
        if (Key == args.Key)
            InvokeActions(Key);
    }  
}

此外,您仍然需要将此附加到 Popup 的子级,而不是 Popup 本身。处理程序在KeyDown附加到 时不会触发Popup,原因只有知道微软秘密专有代码的人知道。

<Popup IsOpen="True">
    <StackPanel>

        <i:Interaction.Triggers>
            <local:KeyTriggerThatWorks Key="Enter">
                <ei:ChangePropertyAction TargetName="alert" PropertyName="Visibility" Value="Visible" />
            </local:KeyTriggerThatWorks>
        </i:Interaction.Triggers>

        <TextBox />
        <TextBlock Text="hi" x:Name="alert" Visibility="Collapsed"/>
    </StackPanel>
</Popup>
于 2013-11-06T20:31:30.890 回答