DependencyProperty值未通过数据绑定设置

时间:2010-01-15 16:36:33

标签: wpf data-binding binding dependency-properties

我有一个有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时,我没有得到绑定源的值。我做错了什么?

1 个答案:

答案 0 :(得分:4)

不幸的是,问题不在我分享的任何代码中。事实证明,我在SomeClass中声明为资源的UserControl实例未使用与DataContext相同的UserControl。我有这个:

<UserControl.Resources>
    <local:SomeClass x:Key="SomeClass" SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />
</UserControl.Resources>

由于SomeClass对象没有权限DataContext,因此未设置DependencyProperty ...