更新时间:2022-05-20 02:57:33
您将控件中的DataContext设置为其自身,从而在其他控件中使用此控件时会覆盖DataContext.以您的情况为例:
You set the DataContext in the Control to itself, thus overwriting the DataContext when using this Control in other controls. Taking your binding as example in your situation:
<src:BlueTextBox BlueText="{Binding Path=MyString}" />
一旦加载并设置了所有Datacontext,由于将DataContext设置为它,它将在BlueTextBox控件中寻找MyString路径.我想这不是您打算的工作方式;).
Once loaded and all the Datacontext is set, it will look for the path MyString in your BlueTextBox thing control due to you setting the DataContext to it. I guess this is not how you intended this to work ;).
解决方案:
更改文本绑定为2个绑定之一:
Change the text binding either one of the 2 bindings:
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:BlueTextBox}}, Path=BlueText}
或
命名您的控件根(或类似名称)
Name your control Root (or something like that)
<UserControl x:Name="Root"
{Binding ElementName=Root, Path=BlueText}
然后删除
DataContext = this;
来自UserControl的构造函数,它应该像超级按钮一样工作.
from the constructor of your UserControl and it should work like a charm..