gpt4 book ai didi

c# - 如何将 DataContext 设置为 self

转载 作者:行者123 更新时间:2023-11-30 20:52:55 24 4
gpt4 key购买 nike

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

为了绑定(bind)到祖先,我正在使用

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

要将控件绑定(bind)到后面的代码(并因此使用“本地”DataContext),我正在使用

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

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

this.MyName.DataContext = this;

上面的工作正常,我可以在其中绑定(bind)到代码隐藏和祖先。

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

我试过了

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

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

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

System.Windows.Data Error: 40 : BindingExpression path error: 'MyUC3Property' property not found on 'object' ''TextBlock' (Name='')'. BindingExpression:Path=MyUC3Property; DataItem='TextBlock' (Name=''); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

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

最佳答案

您应该能够像绑定(bind)到窗口一样绑定(bind)到用户控件:

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

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

关于c# - 如何将 DataContext 设置为 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20420001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com