【发布时间】: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