如何将简单的字符串值绑定到文本框?

我正在使用wpf。 我想绑定一个文本框,其中包含在xaml.cs类中初始化的简单字符串类型值。 TextBox没有显示任何内容。 这是我的XAML代码:

  

而C#代码是这样的:

 public partial class EntitiesView : UserControl { private string _name2; public string Name2 { get { return _name2; } set { _name2 = "abcdef"; } } public EntitiesView() { InitializeComponent(); } } 

您永远不会设置您的财产的价值。 只需定义set { _name2 = "abcdef"; } 在实际执行set操作之前,实际上并未设置属性的值。

您可以将代码更改为以下内容:

 public partial class EntitiesView : UserControl { private string _name2; public string Name2 { get { return _name2; } set { _name2 = value; } } public EntitiesView() { Name2 = "abcdef"; DataContext = this; InitializeComponent(); } } 

此外,正如人们所提到的,如果您打算稍后修改属性的值并希望UI反映它,则需要实现INotifyPropertyChanged接口:

 public partial class EntitiesView : UserControl, INotifyPropertyChanged { private string _name2; public string Name2 { get { return _name2; } set { _name2 = value; RaisePropertyChanged("Name2"); } } public EntitiesView() { Name2 = "abcdef"; DataContext = this; InitializeComponent(); } public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } 

只需在EntitiesView构造函数中添加此行即可

 DataContext = this; 

为什么不添加视图模型并保留您的财产?

查看模型类

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace WpfApplication1 { public class TestViewModel : INotifyPropertyChanged { public string _name2; public string Name2 { get { return "_name2"; } set { _name2 = value; OnPropertyChanged(new PropertyChangedEventArgs("Name2")); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } } } 

EntitiesView用户控件

 public partial class EntitiesView : UserControl { public EntitiesView() { InitializeComponent(); this.DataContext = new TestViewModel(); } }