【发布时间】:2015-07-23 08:39:11
【问题描述】:
我在我制作的“按钮”自定义控件中创建了一个 DP:
#region IsPressed
public bool IsPressed {
get { return (bool)GetValue(IsPressedProperty); }
private set { SetValue(IsPressedProperty, value); }
}
private static void IsPressedCallback(DependencyObject o, DependencyPropertyChangedEventArgs args) {
MyParentClass btn = (MyParentClass) o;
//change the background when the "button" is pressed, change it back afterward
if ((bool) args.NewValue) {
btn._backgroundBrushTemp = btn.Background;
btn.Background = btn._pressBrush;
} else {
btn.Background = btn._backgroundBrushTemp;
}
}
private readonly static PropertyMetadata IsPressedMetadata = new PropertyMetadata() {
DefaultValue = false,
PropertyChangedCallback = IsPressedCallback
};
public static readonly DependencyProperty IsPressedProperty =
DependencyProperty.Register("IsPressed", typeof(bool), typeof(MyParentClass), IsPressedMetadata);
#endregion
一切都按预期工作,但用户现在想要一种新行为,使我的自定义控件不那么通用,因此我创建了另一个自定义控件:继承 MyParentClass 的 MyChildrenClass。
为了实现新行为,我必须重写 IsPressed 的回调函数,所以我在 MyChildrenClass 的静态 ctor 中编写了这个:
IsPressedProperty.OverrideMetadata(
typeof(MyChildrenClass),
new FrameworkPropertyMetadata(false, IsPressedCallback)
);
并写了新的回调:
private static void IsPressedCallback(DependencyObject o, DependencyPropertyChangedEventArgs args) {
MyChildrenClass btn = (MyChildrenClass)o;
//change the background when the "button" is pressed, change it back after 1s
if ((bool) args.NewValue) {
btn._backgroundBrushTemp = btn.Background;
btn.Background = btn._pressBrush;
if (btn._threadIsPressed == null ||
!btn._threadIsPressed.IsAlive) {
btn._threadIsPressed = new Thread(() => {
Thread.Sleep(1000);
btn.Dispatcher.BeginInvoke(new Action(() => {
btn.Background = btn._backgroundBrushTemp;
}));
});
btn._threadIsPressed.Start();
}
}
}
现在的问题是:即使我已经覆盖了元数据和回调函数,两个回调都被调用了。我做错了什么?
【问题讨论】:
-
您希望派生类更改基类的行为。这确实是错误的,所以无论你试图解决什么问题,这都不是一个干净的解决方案。
标签: c# wpf custom-controls dependency-properties