2014-09-12 105 views
0

我希望有人能給我一個正確的方向踢,我目前正在學習WPF和MVVM - 讓我們說它不是一帆風順。基本上我試圖訪問DataContext的屬性,並將它們綁定到我的視圖中的屬性。我會完全誠實的,我陷入了一陣糾結。訪問視圖中的DataContext屬性

當用戶點擊相關按鈕時,它會觸發下面的代碼。

private void OnReceiptClick(object sender, RoutedEventArgs e) 
    { 
     var dialogBox = new DisplayReceiptView(((CheckMemberViewModel) this.DataContext).ReceiptViewModel); 
     dialogBox.ShowDialog(); 
    } 

我CheckMemberViewModel目前持有的「人」屬性我之後,在這個階段的DataContext如預期的那樣填充。

我DisplayReceiptView背後的代碼如下所示:

public DisplayReceiptView(ReceiptViewModel context) : this() 
    { 
     this.DataContext = context; 
    } 

再次一切似乎是正確的,最後在我的XAML我有

<Grid DataContext="{Binding Path=Person}"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="10"/> 
      <ColumnDefinition Width="150"/> 
      <ColumnDefinition Width="*"/> 
     </Grid.ColumnDefinitions> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="10" /> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="Auto"/> 
     </Grid.RowDefinitions> 
     <Label Grid.Column="1" Grid.Row="1">Name:</Label> 
     <TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox> 
     </Grid> 

不幸的是,無論我做什麼,而且我認爲我現在所處的位置是距離我最近的地方,這些數據似乎並不具有約束力。以下是我的ViewModel代碼的屬性

 private Person _person; 
     public Person Person 
    { 
     get { return _person; } 
     set 
     { 
      if (value != _person) 
      { 
       _person = value; 
       OnPropertyChanged("Person"); 
      } 
     } 
    } 

任何幫助,非常感謝。

回答

1
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox> 

這是錯了,因爲你已經綁定到人

<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename}"></TextBox> 

是所有你需要

<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename, Mode=TwoWay}"></TextBox> 

將更改保存到源和檢索的變化,當然你會需要保存上下文更改以使它們永久保存

+0

同意 - 通常您不綁定到ABCD,其中這些代表屬性鏈和子屬性。您將數據源設置爲A.B.C,然後綁定到D - 鏈中的最後一個屬性。通知僅限於該財產。 – Dean 2014-09-13 03:01:13