将标签内容绑定到自字符串字段但没有结果
我正在尝试在我的用户控件中进行简单的绑定:
<UserControl x:Class="MyApp.FlowNode" ...>
<StackPanel>
<Label Content="{Binding Path=Header, RelativeSource={RelativeSource Self}}" />
</StackPanel>
</UserControl>
底层代码是:
public partial class FlowNode : UserControl
{
public FlowNode()
{
InitializeComponent();
}
public string Header { get { return "Testing"; } };
}
但是,标签保持空白。我做错了什么?
I'm trying what should be an easy bind in my user control:
<UserControl x:Class="MyApp.FlowNode" ...>
<StackPanel>
<Label Content="{Binding Path=Header, RelativeSource={RelativeSource Self}}" />
</StackPanel>
</UserControl>
With the underlying code being:
public partial class FlowNode : UserControl
{
public FlowNode()
{
InitializeComponent();
}
public string Header { get { return "Testing"; } };
}
However, the label stays blank. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
{RelativeSource Self}
指的是Label
实例,而不是您的用户控件。您应该将 UserControl 的 DataContext 设置为其自身,而不是使用
RelativeSource
,如 karmicpuppet 建议的那样。{RelativeSource Self}
refers to theLabel
instance, not your user control.Instead of using a
RelativeSource
, you should set the UserControl'sDataContext
to itself, as karmicpuppet suggested.尝试使用
Try to use
在构造函数中,将 UserControl 的 DataContext 设置为其自身。 “这个.DataContext = 这个”。并删除绑定中的RelativeSource。
In your constructor, set the DataContext of the UserControl to itself. "this.DataContext = this". And remove the RelativeSource in your binding.
我认为在 xaml 中访问“Me”/“this”的最方便方法是在控件上添加一个名称:
<用户控制
x:Class="MyApp.FlowNode"
...
名称=“MyFlowNode”>
然后,如果绑定到控件的属性或 dp,则使用 ElementName 语法。
因此,您不会破坏控件的 DataContext。
可能有一种方法可以使用RelativeSource FindAncestor 绑定,但我没有看到比该方法有什么优势。
但是不要将控件的DataContext设置为其自身,否则它将失去对其DataContext的感知。
The most convenient way to get access to 'Me'/'this' in xaml in my opinion is to put a Name on your control :
< UserControl
x:Class="MyApp.FlowNode"
...
Name="MyFlowNode" >
And then, if you bind to your control's property or dp, you use ElementName syntax.
So you don't break the DataContext of your control.
There might be a way with RelativeSource FindAncestor binding, but i don't see advantages over that one.
But do not set DataContext of your Control to itself, otherwise it will loose awareness of its DataContext.