2012-03-13 31 views
3

我從空白的全景項目複製了代碼並做了一些調整,但是某處不對。我的數據綁定有什麼問題?

我有我的文字塊設置:

<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding ElementName=CurrentPlaceNow, Path=Temperature}" /> 

我的模型看起來是這樣的:

public class CurrentPlaceNowModel : INotifyPropertyChanged 
{ 
    #region PropertyChanged() 
    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(String propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (null != handler) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
    #endregion 

    private string _temperature; 
    public string Temperature 
    { 
     get 
     { 
      return _temperature; 
     } 
     set 
     { 
      if (value != _temperature) 
      { 
       _temperature = value; 
       NotifyPropertyChanged("Temperature"); 
      } 
     } 
    } 
} 

而在MainViewModel()定義定義:

public CurrentPlaceNowModel CurrentPlaceNow = new CurrentPlaceNowModel(); 

最後我我添加了一個修改器buttonclick:

App.ViewModel.CurrentPlaceNow.Temperature = "foo"; 

現在,爲什麼沒有任何東西顯示在文本框中?

回答

4

你的綁定應該瀏覽ViewModel。綁定到ElementName會嘗試查看Visual Tree中的另一個對象。

更改綁定到這一點:

<TextBlock 
    Grid.Column="0" 
    Grid.Row="0" 
    Text="{Binding CurrentPlaceNow.Temperature}" /> 

驗證您的視圖模型的財產格式正確:

private CurrentPlaceNowModel _CurrentPlaceNow = new CurrentPlaceNowModel(); 
public CurrentPlaceNowModel CurrentPlaceNow 
{ 
    get { return _CurrentPlaceNow; } 
    set 
    { 
     _CurrentPlaceNow = value; 
     NotifyPropertyChanged("CurrentPlaceNow"); 
    } 
} 

只要你查看的DataContext的是你MainViewModel,你是好去。

+0

現貨,謝謝!完全忘記了_CurrentPlaceNow的獲取/設置 – Jason94 2012-03-13 19:42:22

0

您正在使用ElementName錯誤。 ElementName是當你想綁定到另一個XAML控件,而不是(查看)模型。

要綁定到模型,請將該模型的實例設置爲DataContext屬性並僅綁定Path。