3

我想在 XAML 字典中使用RoutedEventa 。Border来自模板所在的RoutedEvent类,我该如何实现?

现代窗口.cs

/// <summary>
/// Gets fired when the logo is clicked.
/// </summary>
public static readonly RoutedEvent LogoClickEvent = EventManager.RegisterRoutedEvent("LogoClickRoutedEventHandler", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ModernWindow));

/// <summary>
/// The routedeventhandler for LogoClick
/// </summary>
public event RoutedEventHandler LogoClick 
{
    add { AddHandler(LogoClickEvent, value); }
    remove { RemoveHandler(LogoClickEvent, value); }
}

/// <summary>
/// 
/// </summary>
protected virtual void OnLogoClick() 
{
    RaiseEvent(new RoutedEventArgs(LogoClickEvent, this));
}

现代窗口.xaml

<!-- logo -->
<Border MouseLeftButtonDown="{TemplateBinding LogoClick}" Background="{DynamicResource Accent}" Width="36" Height="36" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,76,0">
    <Image Source="{TemplateBinding Logo}" Stretch="UniformToFill" />
</Border>
4

2 回答 2

2

我认为在您的情况下,您可以使用EventSetter,它就是为此而设计的。对你来说,它看起来像这样:

<Style TargetType="{x:Type SomeControl}">
    <EventSetter Event="Border.MouseLeftButtonDown" Handler="LogoClick" />
    ...

</Style>

Note: EvenSetter不能通过触发器设置,也不能用于主题资源字典中包含的样式,因此通常放在当前样式的开头。

有关更多信息,请参阅:

MSDN 中的 EventSetter 类

或者,如果您需要在 a 中使用它ResourceDictionary,您可以采用不同的方式。创建DependencyProperty(也可以附加)。附上的例子DependencyProperty

属性定义:

public static readonly DependencyProperty SampleProperty =
                                          DependencyProperty.RegisterAttached("Sample",
                                          typeof(bool),
                                          typeof(SampleClass),
                                          new UIPropertyMetadata(false, OnSample));

private static void OnSample(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    if (e.NewValue is bool && ((bool)e.NewValue) == true)
    {
        // do something...
    }
}

如果您尝试设置我们的属性的值,称为On Sample,您将能够在其中做您需要的事情(几乎和事件一样)。

根据事件设置属性的值,您可能会喜欢:

<EventTrigger SourceName="MyBorder" RoutedEvent="Border.MouseLeftButtonDown">
    <BeginStoryboard>
        <Storyboard>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="MyBorder" Storyboard.TargetProperty="(local:SampleClass.Sample)">
                <DiscreteObjectKeyFrame KeyTime="0:0:0">
                    <DiscreteObjectKeyFrame.Value>
                        <sys:Boolean>True</sys:Boolean>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>
    </BeginStoryboard>
</EventTrigger>
于 2013-08-07T05:30:07.827 回答
2

我终于找到了一个解决方案,我使用了InputBindings然后Commands.

<Border.InputBindings>
    <MouseBinding Command="presentation:Commands.LogoClickCommand" Gesture="LeftClick" />
</Border.InputBindings>

这不是我想要的,但它有效:)

于 2013-08-07T13:19:36.653 回答