想我再也以下的DependencyObject類型,爲什麼ValidateValueCallback調用兩次?
public class Test : DependencyObject
{
public int Order
{
get { return (int)GetValue(OrderProperty); }
set { SetValue(OrderProperty, value); }
}
public static readonly DependencyProperty OrderProperty =
DependencyProperty.Register("OrderProperty",
typeof(int),
typeof(Test),
new FrameworkPropertyMetadata(6,
new PropertyChangedCallback(OnOrderPropertyChanged),
new CoerceValueCallback(OnCoerceValueCallBack)),
new ValidateValueCallback(OnValidateValueCallBack));
static void OnOrderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine("OnOrderPropertyChanged");
}
static object OnCoerceValueCallBack(DependencyObject d, object baseValue)
{
Console.WriteLine("OnCoerceValueCallBack");
return 200;
}
static bool OnValidateValueCallBack(object value)
{
Console.WriteLine("OnValidateValueCallBack");
int iValue = (int)value;
return iValue > 5;
}
}
當我創建測試的一個實例,我看到OnValidateValueCallBack
被稱爲兩次,OnCoerceValueCallBack
完全不叫。根據我所看到的,我猜想當我創建實例時,WPF將調用OnValidateValueCallBack
來檢查默認值是否有效,如果是,它將使用默認值,根本不會調用CoerceValueCallback
,那麼第二個來電OnValidateValueCallBack
來自哪裏?
設置一個斷點並使用堆棧跟蹤。 – Val 2010-09-27 13:21:33