我希望能够在WPF应用程序中实现一组类似的附加行为。由于它们都共享一部分样板代码,我不想为每个行为重复编写,因此我想创建一个基本行为并从中继承。
但由于附加行为内部的所有内容都是静态的,我不知道该如何做。
例如,考虑这个行为,它会在鼠标按下时执行一个方法(真正的行为当然会做一些事件处理程序无法轻易完成的事情):
例如,考虑这个行为,它会在鼠标按下时执行一个方法(真正的行为当然会做一些事件处理程序无法轻易完成的事情):
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 实现,以及一些额外的属性来控制它。应该如何做?