2012-03-29 71 views
1

我加入的.csTextBlock綁定?

public static readonly DependencyProperty lbStatusProperty = 
     DependencyProperty.Register("lbStatus", typeof(string), typeof(SingleTalkView), 
     new PropertyMetadata("")); 

    public string lbStatus 
    { 
     get { return (string)GetValue(lbStatusProperty); } 
     set { SetValue(lbStatusProperty, value); } 
    } 

在XAML

<TextBlock Text="{Binding lbStatus}" Style="{StaticResource PhoneTextNormalStyle}" Height="24"/> 

然後代碼添加一個全局值

private string a = "Test"; 

和初始化函數

this.lbStatus = a; 

決賽我添加一個按鈕並更改a值,TextBlock不會改變!爲什麼? Thx ~~~~

回答

1

.NET中的字符串是不可變的類型。如果鍵入:

this.lbStatus = a; 

您設置lbStatus對當前由a變量指向的字符串的引用。後來,當你改變:

a = "Foo"; 

你不打算改變this.lbStatus,因爲你分配a變量到一個完全新的字符串實例。

+0

哦......我如何結合TextBlock的? – Yagami 2012-03-29 05:38:44

+0

@Yagami通常,你會綁定到實現INotifyPropertyChanged的類的Property。你可以參考我關於WPF數據綁定的文章,這與Windows Phone中的綁定非常相似:http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-形式對WPF與 - MVVM部分-4-數據綁定/ – 2012-03-29 05:42:01

0

這可以幫助你更好地瞭解

public class Base : INotifyPropertyChanged 
    {  
     public event PropertyChangedEventHandler PropertyChanged;  
     protected void NotifyPropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     }  
    } 

//ViewModel 
public class ViewModel : Base 
private string _value; 
     public string value { 
      get 
      { 
       return _value; 
      } 
      set 
      { 
       _value = value; 
       this.NotifyPropertyChanged("value"); 
      } 
     } 
//View 
<Textbox Height="60" Width="60" Foreground="Wheat" 
         Text="{Binding value,Mode=TwoWay}" >