将控件绑定到该对象的代码隐藏属性

发布于 2024-12-25 10:40:26 字数 314 浏览 0 评论 0原文

我想将 Label 控件绑定到代码隐藏类中有一个属性:

    public MainWindow()
    {
        InitializeComponent();
        this.Label1Content = "some text";
    }

    public string Label1Content { get; set; }

但绑定失败。显然我在绑定配置中遗漏了一些东西,但我不知道是什么。我知道如何使用 C# 绑定此属性,但如何使用 XAML 绑定它而不声明 DataContext?

I have a property in a code-behind class to which I want to bind my Label control:

    public MainWindow()
    {
        InitializeComponent();
        this.Label1Content = "some text";
    }

    public string Label1Content { get; set; }

But the binding fails. Obviously I am missing something in the binding configuration, but I don't know what. I know how to bind this property using C#, but how do I bind it using XAML and without declaring DataContext?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

ゞ花落谁相伴 2025-01-01 10:40:26

如果您不想在任何地方声明数据上下文,您可以使用

<Label Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=Label1Content}" />

If you don't want to declare a datacontext anywhere, you could use

<Label Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=Label1Content}" />
深府石板幽径 2025-01-01 10:40:26

即使它是同一个控件,您仍然必须声明 DataContext

public MainWindow()
{
    InitializeComponent();

    DataContext = this;

    this.Label1Content = "some text";
}

此外,该控件必须实现 INotifyPropertyChanged,以便您可以引发 PropertyChanged代码>事件。你的财产应该是独立的,如下所示:

public string _lable1Content;
public string Label1Content
{
    get { return _label1Content; }
    set
    {
        if (Equals(value, _label1Content)) return;

        _label1Content = value;

        //However you decide to implement the RaisePropertyChanged method.
    }
}

You still have to declare a DataContext, even if it is the same control:

public MainWindow()
{
    InitializeComponent();

    DataContext = this;

    this.Label1Content = "some text";
}

Also, the control will have to implement INotifyPropertyChanged so you can raise the PropertyChanged event. You're property should be self-contained like so:

public string _lable1Content;
public string Label1Content
{
    get { return _label1Content; }
    set
    {
        if (Equals(value, _label1Content)) return;

        _label1Content = value;

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