WPF:简单的文本框数据绑定 [英] WPF: simple TextBox data binding

查看:14
本文介绍了WPF:简单的文本框数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这门课:

public partial class Window1 : Window
{
    public String Name2;

    public Window1()
    {
        InitializeComponent();
        Name2 = new String('a', 5);
        myGrid.DataContext = this;
    }

    // ...
}

我想在文本框中显示字符串 Name2.

And I want to display the string Name2 in the textbox.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2}"/>
</Grid>

但是没有显示字符串.另外,如果字符串 Name2 使用 TimerCallback 定期更新,我是否需要做任何事情来确保在数据更改时更新文本框?

But the string isn't displayed. Also, if the string Name2 is updated periodically using a TimerCallback, do I need to do anything to make sure the textbox is updated when the data changes?

推荐答案

Name2 是一个字段.WPF 仅绑定到属性.将其更改为:

Name2 is a field. WPF binds only to properties. Change it to:

public string Name2 { get; set; }

请注意,使用这种最小实现,您的 TextBox 将不会响应对 Name2 的编程更改.因此,对于您的计时器更新方案,您需要实现 INotifyPropertyChanged:

Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:

partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  private string _name2;

  public string Name2
  {
    get { return _name2; }
    set
    {
      if (value != _name2)
      {
         _name2 = value;
         OnPropertyChanged("Name2");
      }
    }
  }
}

您应该考虑将其移至单独的数据对象而不是您的 Window 类.

You should consider moving this to a separate data object rather than on your Window class.

这篇关于WPF:简单的文本框数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆