【问题标题】:How do I avoid binding to 2 datacontext如何避免绑定到 2 个数据上下文
【发布时间】:2014-02-26 22:29:30
【问题描述】:

我的应用程序如下所示

黑色是我的MainWindow,红色是标签控件,黄色是UserControl。

UserControl 定义了许多依赖属性,它们绑定到 DataContext(在 MainWindow 后面的代码中设置,使用 this.DataContext = this)。

要将我的 UserControl 绑定到与我的 MainWindow 相同的 DataContext,在我的 UserControl xaml 中我有以下

DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1,AncestorType=Window}}"

这很好用,当我与我的 UserControl 交互时,由于双向绑定,它会更新我的 MainWindow 的属性,这反过来会更新我的 TabControl!

问题是,我的 UserControl 现在有一些额外的功能,因此需要绑定到 UserControl 背后的代码(例如 GUI 的值)。

这就是我卡住的地方。我无法从我的 UserControl 绑定到后面的代码,因为我已经创建了一个 DataContext。

我知道我可以使用 WinForms 方法,并使用 x:Name="MyControl" 为每个控件命名

MyControl.Text = "This value";

MyControl.DataContext = this;

哎呀我想!!

我的问题是,这是唯一的方法,还是我仍然可以使用绑定。

【问题讨论】:

    标签: c# wpf user-controls dependency-properties


    【解决方案1】:

    您可以像 MainWindow 属性一样使用另一个 RelativeSource Binding... 来访问在 UserControl 中定义的属性,在您的 UserControl 中尝试以下 XAML:

    <TextBlock Text="{Binding UserControlProperty, RelativeSource={RelativeSource 
        AncestorType={x:Type YourXmlNamespacePrefix:YourUserControl}}}" />
    

    显然,您需要将 YourXmlNamespacePrefix:YourUserControl 更新为有效的 XML 命名空间和控件类型才能使其正常工作。


    不是说您应该在任何地方设置DataContext,或者更改任何属性。这是RelativeSource Binding...您确实需要设置任何DataContext 才能使其工作。我以为你会知道,因为你已经在使用一个。试试这个例子吧。

    【讨论】:

    • 对不起,我迷路了。所以,这意味着,我的 UserControl 将绑定到它自己的 DataContext(在这种情况下是后面的代码),并且我为 UserControl 中需要绑定到 MainWindow 的 DataContext 的每个控件使用 RelativeSource?我的 MainWindow 只有 this.DataContext = this;
    【解决方案2】:

    首先,您不需要在 UserControl 上手动设置DataContextDataContext 是一个可继承属性,因此除非您明确设置它,否则它将从其父级继承 DataContext

    从您的 UserControl 中删除 DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1,AncestorType=Window}}"


    现在,如果您想为 UserControl 中的某些控件绑定代码,您可以使用RelativeSource 进行绑定,也可以在控件上设置DataContext

    DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
                                                         AncestorType=UserControl}}"
    

    如果控件可以在一个面板下组合在一起,则在父面板上设置 DataContext 说 Grid 和子控件将从它继承:

    <Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
                                                AncestorType=UserControl}}">
       ..Child Controls here will inherit DataContext
    </Grid>
    

    回答你的问题:

    MyControl.DataContext = 这个;

    是的,就像我上面提到的那样。

    【讨论】:

    • 我知道它是遗传的——你以前告诉过我,但我仍然坚持要放进去!!唉……总有一天我会学会的!!你又给我修好了!谢谢。
    • 哦,是吗?我猜它会在圈子里回到你身边.. :) 不客气,戴夫..!!祝你有美好的一天.. :)
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多