2013-07-20 52 views
0

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

你可以发布你的XAML吗? – Kurubaran

+0

@Coder我发布了它。请参阅第一行代码。

+0

你认为你在哪里设置值什么? –

回答

6

你永远不设置你的财产的价值。在您实际执行设置操作之前,只需定义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(); 
    } 
} 

而且,人们已经提到的,如果你打算以后修改你的财产的价值,并希望用户界面,以反映它,您需要实现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)); 
     } 
    } 
} 
+0

很抱歉,关于这么晚的回复,但表单控件如何订阅PropertyChangedEventHandler? – William

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

只是在你EntitiesView构造函数中加入这一行

DataContext = this; 
相关问题