我想在XAML词典中的RoutedEvent
上使用Border
。 RoutedEvent
来自模板所在的类,我该如何实现?
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>
答案 0 :(得分:2)
我最终找到了一个解决方案,我使用InputBindings
然后使用Commands
。
<Border.InputBindings>
<MouseBinding Command="presentation:Commands.LogoClickCommand" Gesture="LeftClick" />
</Border.InputBindings>
这不是我想要的,但它有效:)
答案 1 :(得分:1)
我认为在您的情况下,您可以使用EventSetter
,它只是为此而设计的。对你而言,它看起来像这样:
<Style TargetType="{x:Type SomeControl}">
<EventSetter Event="Border.MouseLeftButtonDown" Handler="LogoClick" />
...
</Style>
无法通过触发器设置 Note:
EvenSetter
,并且无法在主题资源字典中包含的样式中使用,因此通常将其放在开头目前的风格。
有关详细信息,请参阅:
或者,如果您需要在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>