views:

346

answers:

1

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?

A: 

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

emddudley