C# 依附行为的继承
我想在WPF应用程序中实现一组类似的附加行为。 由于它们都共享一块样板代码,我不想对每个样板代码都重复,所以我想创建一个从中继承的基本行为。 但是,由于附加行为中的所有内容都是静态的,所以我不知道如何做 以这个行为为例,它在mousedown上执行一个方法(真正的行为当然会做一些在eventhandler中不容易做的事情):C# 依附行为的继承,c#,wpf,C#,Wpf,我想在WPF应用程序中实现一组类似的附加行为。 由于它们都共享一块样板代码,我不想对每个样板代码都重复,所以我想创建一个从中继承的基本行为。 但是,由于附加行为中的所有内容都是静态的,所以我不知道如何做 以这个行为为例,它在mousedown上执行一个方法(真正的行为当然会做一些在eventhandler中不容易做的事情): 现在,我想创建一个新的行为,它应该有MyMethod的不同实现,以及控制它的一些附加属性。应该如何实现这一点?您可以创建另一个附加属性,该属性包含由主行为调用作为子类替换的
现在,我想创建一个新的行为,它应该有MyMethod的不同实现,以及控制它的一些附加属性。应该如何实现这一点?您可以创建另一个附加属性,该属性包含由主行为调用作为子类替换的详细实现。属性所持有的对象可以是非静态的,并且可以像对象一样使用
(您可能也可以将其放入一个属性中,其中
property==null
表示关闭)您可以使用静态构造函数来形成字典
来将特定的DP映射到特定的处理程序,并使用公共的DependencyPropertyChanged
回调:
static StupidBehavior()
{
handlerDictionary[IsEnabledProperty] = (o,e) => MyMethod();
handlerDictionary[SomeOtherProperty] = (o,e) => SomeOtherMethod();
}
private static void CommonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
var uie = sender as UIElement;
if (uie != null)
{
//removing before possibly adding makes sure the multicast delegate only has 1 instance of this delegate
sender.MouseDown -= handlerDictionary[args.Property];
if (args.NewValue != null)
{
sender.MouseDown += handlerDictionary[args.Property];
}
}
}
或者只需在args.Property
上执行开关
。或者介于两者之间的东西,它涉及一个公共方法和基于dependencProperty
的分支
我不知道为什么你的
IsEnabled
属性处理的是dependencProperty类型的值,而不是像bool
这样更具语义的值。当孩子继承愚蠢的行为时,总是很遗憾。谢谢!这确实应该是布尔。复制粘贴错误=)
static StupidBehavior()
{
handlerDictionary[IsEnabledProperty] = (o,e) => MyMethod();
handlerDictionary[SomeOtherProperty] = (o,e) => SomeOtherMethod();
}
private static void CommonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
var uie = sender as UIElement;
if (uie != null)
{
//removing before possibly adding makes sure the multicast delegate only has 1 instance of this delegate
sender.MouseDown -= handlerDictionary[args.Property];
if (args.NewValue != null)
{
sender.MouseDown += handlerDictionary[args.Property];
}
}
}