【问题标题】:Bind button content to a variable将按钮内容绑定到变量
【发布时间】:2018-09-03 13:35:21
【问题描述】:

我在 XAML 中有以下内容:

<Button Content="{Binding KB.Text}" />

KB 是以下类的一个实例:

public class ButtonText
    {
        public string Text
        {
            get
            {
                return "Button";
            }
        }
    }

我在页面后面的代码中将KB定义为全局变量,运行项目时按钮内容显示为空,我该如何实现?按钮内容应由 KB.Text 检索

【问题讨论】:

  • 您可以向MainWindow.DataContext 显示您正在设置的内容吗?
  • this.DataContext = this;

标签: c# button uwp


【解决方案1】:
  • 确保您的“KB”对象已初始化(非空)。

  • 您可能在主函数中错过了“this.DataContext = this”

  • 确保您的知识库是财产

这对我有用:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        KB = new ButtonText();
    }

    public ButtonText KB { get; }

}
public class ButtonText
{
    public string Text
    {
        get
        {
            return "Button";
        }
    }
}

编辑: 我写了第一个考虑 WPF 的解决方案,花了我一段时间才发现有一个“UWP”标签。

在 UWP 中,如果你想将某些东西绑定到设计器本身背后的代码 (*xaml.cs),你应该使用“x:Bind”而不是“Binding”。

见link about x:Bind vs Binding

简而言之,您的 xaml 应该如下所示:

<Button Content="{x:Bind KB.Text}"/>

【讨论】:

  • 嗯,对我不起作用,是不是因为我的主类继承自 Page 而不是 Window?或者我可能需要定义一个 xmlns 属性?我也在一个新项目中尝试过。
  • @Ham.Abdu2 抱歉,我忘了它是 UWP 而不是 WPF。我更新了我的答案
  • 这应该如何工作?设置数据上下文后初始化 KB,因此 UI 不会有正确的值。此外,如果没有 INotifyPropertyChanged,对 KB 的进一步更改也不会通知 UI。
猜你喜欢
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多