DependencyProperty value not getting set through data binding

不羁的心 提交于 2020-01-02 05:38:08

问题


I have a class which has a DependencyProperty member:

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
    }
}

The property is bound in XAML:

<local:SomeClass SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />

I'm using MVVM, so my viewmodel is the DataContext for this XAML. The binding source property looks like this:

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;
}

I'm not getting the binding source's value when I access this.SomeValue. What am I doing wrong?


回答1:


Unfortunately, the problem was not in any of the code I shared. It turns out that my SomeClass instance, which I declared as a resource in my UserControl, was not using the same DataContext as the UserControl. I had this:

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

Since the SomeClass object didn't have the right DataContext, the DependencyProperty was not being set...



来源:https://stackoverflow.com/questions/2073170/dependencyproperty-value-not-getting-set-through-data-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!