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

时间:2013-07-20 16:38:52

标签: c# .net wpf xaml

我正在使用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();
    }
}

3 个答案:

答案 0 :(得分:7)

您永远不会设置您的财产的价值。在实际执行set操作之前,简单地定义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));
        }
    }
}

答案 1 :(得分:2)

只需在EntitiesView构造函数

中添加此行
DataContext = this;

答案 2 :(得分:0)

为什么不添加视图模型并将属性保留在那里?

  

查看模型类

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