Cannot databind DependencyProperty

天大地大妈咪最大 提交于 2019-12-03 17:10:19

As sometimes happens, the problem turned out to be not quite what we thought.

I mentioned that the setter was never called. That is true. The code above is slightly trimmed to make it clearer. Unfortunately, I also trimmed away a statement in the setter, following the call to SetValue. That statement assigned the value to DataContext, something like this:

public ViewModelBase ViewModel
{
    get { return GetValue(ViewModelProperty) as ViewModelBase; }
    set
    {
        SetValue(ViewModelProperty, value);
        DataContext = value;
    }
}

As I have now learned from this excellent article, the setter is in fact bypassed when the property is set via databinding. The framework instead works directly against the DependencyObject. So the property was actually set, but the setter was never called (as I mentioned), and the consequence was that DataContext remained null and nothing worked.

So: First I apologize profusely for asking an unanswerable question. Second, as a way of making up for it, I can pass on the very important piece of advice:

Never put anything but GetValue() and SetValue() inside the property getter/setter, because they are not always called!

Edit: Later, I've also discovered another problem with this approach. By setting the DataContext this way, I actually lose the original data context that supports the binding in the first place. The result is that the property is immediately reset to null. So all in all not a good approach overall.

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