【问题标题】:How to bind a label to a field found in the same window class in WPF?如何将标签绑定到 WPF 中同一窗口类中的字段?
【发布时间】:2018-03-05 05:06:18
【问题描述】:

我有一个使用 Visual Studio 模板创建的标准 WPF 应用程序。我的 MainWindow 代码如下所示:

public partial class MainWindow : Window
{
    public MainWindow ( )
    {
        this.InitializeComponent ( );
    }

    string MyValue = "";
}

如何使用 XAML 将我的标签绑定到 MyValue?

【问题讨论】:

  • 不能,因为MyValue是私有字段,只能绑定公共属性。
  • 谢谢,我将其更改为 public,但我无法弄清楚我需要在 XAML 中使用的完整路径才能进行绑定。
  • 显示你需要的结果。
  • 您可以将窗口的数据上下文设置为自身(例如InitializeComponent之前的this.DataContext = this),然后您可以绑定为{Binding MyValue}。但这不是一件好事。或者你可以在 xaml (x:Name=myWindow) 中命名你的窗口,然后你可以绑定{Binding ElementName=myWindow, Path=MyValue}
  • 绑定是什么意思?您想将MyValue 的值传递给Label

标签: c# .net wpf xaml binding


【解决方案1】:

这是我的 .cs 文件:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
    }

    public string MyValue { get; set; } = "Hello";
}

和我的视图文件:

 <Grid>
    <Label Content="{Binding MyValue}"/>
</Grid>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多