如何设置myElement的DataContext的,以相同的DataContext在XAML用户控件?我曾在该用户构造能够做到这一点在code-后面通过 myElement.DataContext = this.DataContext
,但我想知道怎么做同样的事情在XAML。
这关系到创建虚拟分支逻辑树(见本文章)。
<用户控件...的DataContext ={绑定的RelativeSource = {的RelativeSource自我}}>
...
<文本框名称=myTextBox>
< TextBox.Text>
<绑定路径=MYSOURCEUpdateSourceTrigger =的PropertyChanged>
< Binding.ValidationRules>
<基地:StringEqualsRules>
<基地:StringEqualRule.BoundElement>
<基地:ValidationRuleElement
X:名称=myElement
的DataContext =???
值={myProperty的绑定}/>
< /底座:StringEqualRule.BoundElement>
< /底座:StringEqualsRule>
< /Binding.ValidationRules>
< /装订>
< /TextBox.Text>
< /文本框>
...
< /用户控件>
解决方案
使用code-背后竟然是最简单和干净的解决方案,我发现到目前为止:
myElement.DataContext = this.DataContext
How do I set the DataContext of "myElement" to the same DataContext as the user control in XAML? I have been able to do it in code-behind via myElement.DataContext = this.DataContext
in the UserControl constructor, but I'm trying to understand how to do the same thing in XAML.
This is related to creating virtual branches to the logical tree (see this article).
<UserControl ... DataContext="{Binding RelativeSource={RelativeSource self}}">
...
<TextBox Name="myTextBox">
<TextBox.Text>
<Binding Path="MySource" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<base:StringEqualsRules>
<base:StringEqualRule.BoundElement>
<base:ValidationRuleElement
x:Name="myElement"
DataContext="???"
Value="{Binding MyProperty}" />
</base:StringEqualRule.BoundElement>
</base:StringEqualsRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
...
</UserControl>
解决方案
Using code-behind turned out to be the easiest and cleanest solution I've found so far:
myElement.DataContext = this.DataContext