通过TemplateBinding添加RoutedEvent

本文关键字:RoutedEvent 添加 TemplateBinding 通过 | 更新日期: 2023-09-27 18:26:43

我想在XAML字典中的Border上使用RoutedEventRoutedEvent来自模板所在的类,我如何实现这一点?

ModernWindow.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));
}

ModernWindow.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>

通过TemplateBinding添加RoutedEvent

我认为在您的情况下,您可以使用EventSetter,它只是为了做到这一点而设计的。对你来说,它看起来像这样:

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

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

有关更多信息,请参阅:

MSDN 中的EventSetter类

或者,如果您需要在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>

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

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

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