如何将DataContext设置为self

时间:2013-12-06 09:09:47

标签: c# wpf xaml

我的UserControl需要绑定到祖先(祖先是MainWindow)和自身(它的代码隐藏)。

要绑定到祖先,我正在使用

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

要将控件绑定到后面的代码(因此使用'local'DataContext),我正在使用

<TextBlock Text ="{Binding MyUC3Property}" Name="MyName" />

并在后面的代码中,将其设置为

this.MyName.DataContext = this;

以上工作正常,我可以绑定到代码隐藏和祖先。

现在,我仍然希望绑定到后面的代码和祖先,但只在XAML中设置DataContext(如果可能的话)。

我试过

<TextBlock Text ="{Binding MyUC3Property}" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}" /> 

并确保构造函数不设置DataContext(因为我希望它都在XAML中完成) - (尽管即使我设置this.DataContext = this;错误仍然存​​在)

并且输出窗口告诉我存在绑定错误。

  

System.Windows.Data错误:40:BindingExpression路径错误:'object'''TextBlock'(Name ='')'上找不到'MyUC3Property'属性。 BindingExpression:路径= MyUC3Property; DataItem ='TextBlock'(Name =''); target元素是'TextBlock'(Name =''); target属性是'Text'(类型'String')

我想我错过了一些明显的东西,但我不知道是什么。

3 个答案:

答案 0 :(得分:2)

您应该能够以与对窗口相同的方式绑定到用户控件:

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

您尝试过的是指Self中的相对来源TextBox。但是,在该上下文中,Self引用TextBox,而不是封闭的用户控件。

答案 1 :(得分:1)

对于usercontrols,你永远不应该将datacontext设置为self。检查H.B.的评论来自here

我使用ElementName Binding

 <UserControl x:Name="uc">
   <TextBlock Text="{Binding ElementName=uc, Path=MyDependencyPropertyDefinedInMyUserControl}"/>

使用usercontrol:

 <Window>
   <MyUserControl MyDependencyPropertyDefinedInMyUserControl="{Binding Path=MyValueForTheTextBox}"/>

我试着为你的文本框案例解释一下(忽略我的英文不好btw :))

如果你想用文本框创建一个usercontrol,而这个usercontrol / textbox应该在不同的视图中显示来自不同视图模型的文本 - 那么你就会遇到一个问题,只要视图模型有不同的属性名。现在,你的usercontrol中的依赖属性进入游戏。您可以创建一个DP,其中所有视图模型都可以绑定到您的用户控件中的文本框,并将其绑定到用户控件的DP。

答案 2 :(得分:0)

首先,你应该将你的父DataContext推到较低的水平。这将为您提供所有嵌套屏幕之间共享的“上帝”ViewMode

其次,您应该使用类似MVVMLights Messanger的内容来更清晰地分离。