gpt4 book ai didi

c# - 通过 TemplateBinding 添加 RoutedEvent

转载 作者:行者123 更新时间:2023-11-30 22:15:15 27 4
gpt4 key购买 nike

我想在 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>

最佳答案

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

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

</Style>

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

有关详细信息,请参阅:

EventSetter Class in MSDN

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

关于c# - 通过 TemplateBinding 添加 RoutedEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com