我有一个有DependencyProperty
成员的班级:
public class SomeClass : FrameworkElement
{
public static readonly DependencyProperty SomeValueProperty
= DependencyProperty.Register(
"SomeValue",
typeof(int),
typeof(SomeClass));
new PropertyMetadata(
new PropertyChangedCallback(OnSomeValuePropertyChanged)));
public int SomeValue
{
get { return (int)GetValue(SomeValueProperty); }
set { SetValue(SomeValueProperty, value); }
}
public int GetSomeValue()
{
// This is just a contrived example.
// this.SomeValue always returns the default value for some reason,
// not the current binding source value
return this.SomeValue;
}
private static void OnSomeValuePropertyChanged(
DependencyObject target, DependencyPropertyChangedEventArgs e)
{
// This method is supposed to be called when the SomeValue property
// changes, but for some reason it is not
}
}
该属性绑定在XAML中:
<local:SomeClass SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />
我正在使用MVVM,因此我的viewmodel是此XAML的DataContext
。绑定源属性如下所示:
public int SomeBinding
{
get { return this.mSomeBinding; }
set
{
this.mSomeBinding = value;
OnPropertyChanged(new PropertyChangedEventArgs("SomeBinding"));
}
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, e);
}
return;
}
当我访问this.SomeValue
时,我没有得到绑定源的值。我做错了什么?
答案 0 :(得分:4)
不幸的是,问题不在我分享的任何代码中。事实证明,我在SomeClass
中声明为资源的UserControl
实例未使用与DataContext
相同的UserControl
。我有这个:
<UserControl.Resources>
<local:SomeClass x:Key="SomeClass" SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />
</UserControl.Resources>
由于SomeClass
对象没有权限DataContext
,因此未设置DependencyProperty ...