的DependencyProperty价值没有得到通过数据绑定设置 [英] DependencyProperty value not getting set through data binding

查看:562
本文介绍了的DependencyProperty价值没有得到通过数据绑定设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有有一个的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绑定:

The property is bound in XAML:

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

我使用MVVM

,所以我的视图模型是的DataContext 此XAML。绑定源属性看起来是这样的:

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

当我进入我没有收到绑定源的值 this.SomeValue 。我在做什么错了?

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

推荐答案

不幸的是,这个问题是不是在任何code我分享的。事实证明,我的 SomeClass的实例,我声明我在用户控件,并没有使用相同的资源的DataContext 用户控件。我有这样的:

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>

由于 SomeClass的对象没有合适的的DataContext ,将DependencyProperty没有被设置...

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

这篇关于的DependencyProperty价值没有得到通过数据绑定设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆