WPF - 如何在逻辑树的虚拟分支设置的DataContext? [英] WPF - How to set DataContext on virtual branch of logical tree?

查看:279
本文介绍了WPF - 如何在逻辑树的虚拟分支设置的DataContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置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

这篇关于WPF - 如何在逻辑树的虚拟分支设置的DataContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆