wpf重写window样式_关于c#:在WPF中将事件从样式传播到MainWindow

我在单独的XAML CustomTabItem.xaml中有一个自定义样式,该样式引发如下事件:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

x:Class="myProject.CustomTabItem">

...

...

...

...

这很容易在我创建的名为CustomTabItem.xaml.cs的文件中引发一个事件:

namespace myProject

{

partial class CustomTabItem

{

private void ClickNewSpaceOne(object sender, RoutedEventArgs e)

{

//do stuff here

}

}

}

一切正常,但是我现在需要在MainWindow中引发一个事件(当然在事件处理程序ClickNewSpaceOne中),但是我无法弄清楚如何将该事件传播到MainWindow。

我找到了这篇文章,但实际上情况似乎并不一样,因此,我没有找到任何其他不同的文章或我将不胜感激的任何答案。

在这种情况下,使用EventSetter的做法并非最佳。这就是为什么:

他已绑定到BAML文件,并且应该是事件处理程序

因为它仅限于事件的全局功能,所以他只是在xaml.cs文件中查找事件处理程序。另外,由于这个原因,来自MSDN:

Event setters cannot be used in a style that is contained in a theme resource dictionary.

无法在触发器中设置EventSetter

从link引用:

Because using EventSetter to wire up event handler is a compile-time feature which is plumbed through IStyleConnector interface, there is another interface called IComponentConnector which is used by the XAML compiler to wire up event handler for standalone XAML elements.

What alternatives?

1 - Attached dependency property

使用附加的依赖项属性及其UIPropertyMetadata,可以实现必要的逻辑。例如:

// GetValue

// SetValue

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

}

}

更多信息可以在这里找到:

如何继承WPF样式中的Button行为?

从用户控件退出应用程序

登录失败而没有数据绑定时,如何清除PasswordBox的内容?

2 - Commands

WPF中的命令非常强大。从MSDN引用:

The first purpose is to separate the semantics and the object that invokes a command from the logic that executes the command. This allows for multiple and disparate sources to invoke the same command logic, and it allows the command logic to be customized for different targets.

在这种情况下,可以并且应该在Styles,Templates,DataTemplates中使用它们。在样式上,您可以设置如下命令:

Value="{Binding DataContext.YourCommand,

RelativeSource={Relative Source AncestorType={x:Type Control}}}">

另外,如果要引用该命令,则可以将该命令声明为静态属性,然后可以使用Static扩展名来引用它。

3 - Using EventTrigger with Interactivity

在这种情况下,该命令由EventTrigger调用。例如:

更多信息,可以在这里找到:

在XAML中为MVVM使用EventTrigger

将WPF事件绑定到MVVM Viewmodel命令

很好的答案,并提供各种可能的解决方案! 非常感谢您,我将在以后有时间编写代码并在一切正常后接受您的回答时更详细地研究它。 +1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值