2013-07-20 53 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; 
相關問題