Wpf 依赖项属性回调不起作用
我有以下代码:Wpf 依赖项属性回调不起作用,wpf,dependency-properties,Wpf,Dependency Properties,我有以下代码: private static readonly DependencyProperty IDProperty = DependencyProperty.Register( "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged))); public int ID {
private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
"ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged)));
public int ID
{
get { return (int)GetValue(IDProperty); }
set { SetValue(IDProperty, value); }
}
private static void IDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Do something here!
}
我可以看到,当我更改ID时,行SetValue(IPproperty被调用),但它不调用IDChanged
为什么?将DP设置为静态只读。在XAML中设置值时,不使用包装器,直接使用DP。所以,它必须是公开的
但是…显然你是在代码中设置的?在这种情况下,我不知道出了什么问题……但您可以随时尝试。您的代码是正确的,但是PropertyChanged回调在更改之前不会被调用。尝试在连续的代码行中将属性更改为两个不同的值,并有一个断点,您可以看到它已被命中。我相信它被设置为-1,因此它不会被调用。我不知道这个问题是否得到解决,但如果您在使用它的XAML文件中设置值,则在某些情况下,过程代码默认值将成为先例,并且在最初的XAML中设置时不会触发。因此,请删除默认值-1 So
private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
"ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged)));
变成
private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
"ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata( new PropertyChangedCallback(IDChanged)));
有点问题,我无法让它第一次启动,所以我将dependency属性default设置为非标准值,强制它启动回调。