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

Dua*_*Ali 1 .net c# wpf xaml

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

<TextBox Grid.Column="1" Width="387" HorizontalAlignment="Left" Grid.ColumnSpan="2" Text="{Binding Path=Name2}"/>
Run Code Online (Sandbox Code Playgroud)

而C#代码是这样的:

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

Adi*_*ter 7

您永远不会设置您的财产的价值.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,正如人们所提到的,如果您打算稍后修改属性的值并希望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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)