且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能将viewmodel属性绑定到自定义控件的依赖项属性

更新时间:2021-12-25 02:33:51

您正确地认为,如果不绑定到外部视图模型,则UserControl构造函数中的 DataContext = this 短语会优先.在此问题中进行了讨论.但是,这很容易补救.xaml绑定到的UserControl代码中只有一个DependencyProperty:CurrentColor.

这样做:

You are right in thinking that the DataContext=this phrase in the UserControl's constructor preempts if from binding to an external viewmodel. It was disccussed in this question. This is easily remedied however. There is only one DependencyProperty in the UserControl's code behind that the xaml binds to: CurrentColor.

Do this:

  • Name ="Root" 属性添加到UserControl的xaml
  • 更改(边界标签的)属性 Background ="{Path = CurrentColor}"到:

    Background ="{ElementName =根,Path = CurrentColor}"

  • 删除有问题的DataContext = this从UserControl的行构造函数!
  • Add a Name="Root" attribute to the UserControl tag of the UserControl's xaml
  • Change the attribute (of the Border tag) Background="{Binding Path=CurrentColor}" to:

    Background="{Binding ElementName=Root, Path=CurrentColor}"

  • Remove the offending DataContext=this line from the UserControl's constructor!

这应该就是它的全部了.我写了一个概念证明来证明上述内容.如果您愿意,我可以发布它,但是上面的代码应该就是您所需要的.

That should be all that there is to it. I wrote a proof of concept that demonstrates the above. If you like I can post it, but the code above should be all you need.