依赖属性的值无法通过数据绑定设置

4

我有一个类,其中包含一个 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
我读到依赖属性包装器在运行时被WPF绕过,这可能解释了为什么我的断点没有在setter中被触发,但我仍然不知道为什么我无法获取该值... - sourcenouveau
从代码上看,这看起来还不错,这让我想知道上下文是否设置正确。当您在调试器下运行它时,您是否在输出窗口中看到任何数据绑定错误,例如“未找到'SomeBinding'属性...”? - itowlson
1
顺便确认一下,你关于WPF绕过CLR包装属性是正确的,这就是为什么在setter中设置断点不会被触发的原因。 - itowlson
请看我的回答。我现在正在尝试绑定ResourceDictionary中资源的DataContext... https://dev59.com/7kvSa4cB1Zd3GeqPdlrd - sourcenouveau
1个回答

5

很遗憾,问题并不在我分享的任何代码中。事实证明,我在UserControl中声明为资源的SomeClass实例没有使用与UserControl相同的DataContext。我的代码如下:

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

由于SomeClass对象没有正确的DataContext,因此DependencyProperty未被设置...


1
我为此苦苦寻找了很久。对于那些想知道的人,不,控件不会简单地从UserControl继承DataContext。设置this.DataContext = _model是不够的。你必须明确地设置依赖属性所在类的DataContext。 this.DataContext = _model; SomeClass.DataContext = _model; - Tom Padilla
好的,在花费了几个小时来理解我在说什么之后,我明白了发生了什么。在我的自定义控件中,我设置了整个控件的DataContext。这会覆盖任何继承的DataContext。当我设置控件内主Grid的DataContext时,控件本身的DataContext就可以很好地继承了。 - Tom Padilla
哇,我真的感激不尽,我花了好几个小时才弄清楚为什么会发生这种情况。没想到我还需要重新设置数据上下文。 - MrCSharp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接