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

本文关键字:绑定 文本 字符串 简单 | 更新日期: 2023-09-27 18:23:59

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

<TextBox Grid.Column="1" Width="387" HorizontalAlignment="Left" Grid.ColumnSpan="2" Text="{Binding Path=Name2}"/>

C#代码是这样的:

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

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

您从不设置属性的值。在实际执行设置操作之前,简单地定义set { _name2 = "abcdef"; }实际上不会设置属性的值。

你可以把你的代码改成这样让它工作:

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);
            }
        }
    }
}

实体查看用户控制

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