将标签内容绑定到自字符串字段但没有结果

发布于 2024-09-18 00:26:49 字数 502 浏览 2 评论 0原文

我正在尝试在我的用户控件中进行简单的绑定:

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一瞬间的火花 2024-09-25 00:26:50

{RelativeSource Self} 指的是 Label 实例,而不是您的用户控件。

您应该将 UserControl 的 DataContext 设置为其自身,而不是使用 RelativeSource,如 karmicpuppet 建议的那样。

{RelativeSource Self} refers to the Label instance, not your user control.

Instead of using a RelativeSource, you should set the UserControl's DataContext to itself, as karmicpuppet suggested.

等待我真够勒 2024-09-25 00:26:50

尝试使用

{Binding Path=Header, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type FlowNode}}}.

Try to use

{Binding Path=Header, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type FlowNode}}}.
你曾走过我的故事 2024-09-25 00:26:50

在构造函数中,将 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.

若无相欠,怎会相见 2024-09-25 00:26:50

我认为在 xaml 中访问“Me”/“this”的最方便方法是在控件上添加一个名称:
<用户控制
x:Class="MyApp.FlowNode"
...
名称=“MyFlowNode”>
然后,如果绑定到控件的属性或 dp,则使用 E​​lementName 语法。

因此,您不会破坏控件的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文