gpt4 book ai didi

c# - 附加行为的继承

转载 作者:行者123 更新时间:2023-11-30 12:16:08 25 4
gpt4 key购买 nike

我想实现一组类似的附加行为以用于 WPF 应用程序。由于它们都共享一大块样板代码,我真的不想对每个样板代码都重复,所以我想创建一个从中继承的基本行为。但是由于附加行为中的所有内容都是静态的,我不知道该怎么做。

举个例子,以这个行为为例,它在 mousedown 上执行一个方法(真正的行为当然会做一些在事件处理程序中不容易完成的事情):

public static class StupidBehavior
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}

public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}

// Using a DependencyProperty as the backing store for ChangeTooltip. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(StupidBehavior), new UIPropertyMetadata(false, IsEnabledChanged));


private static void IsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((UIElement)sender).MouseDown += { (o,e) => MyMethod(); };
}

private static void MyMethod()
{
MessageBox.Show("Boo");
}
}

现在,我想创建一个新行为,它应该具有 MyMethod 的不同实现,以及一些控制它的附加属性。应该怎么做?

最佳答案

您可以创建另一个附加属性,其中包含由主要行为作为子类替换调用的详细实现。属性持有的对象可以是非静态的,可以像 state-object 一样使用。 .

(您也可以将其放入一个属性中,其中 property == null 表示关闭)

关于c# - 附加行为的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5947984/

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