2013-03-25 67 views
11

我想要的屬性,以綁定一個系列在網格文本框的成對象本身是在我的視圖模型(在DataContext)另一屬性的性質。結合到對象

CurrentPersonNameAge性能

視圖模型內部:

public Person CurrentPerson { get; set ... (with OnPropertyChanged)} 

的XAML:

<TextBox Text="{Binding Name}" > 
<TextBox Text="{Binding Age}" > 

我不知道的方法來使用,我設置另一個DataContext在網格範圍內,沒有任何結果,也嘗試過s如Source = CurrentPerson,Path = Age等源代碼和路徑再次沒有任何結果,這些是用於試驗,看看是否會有任何改變。

我該怎麼做到這一點?

回答

17

請問您的Person班級成員NameAge是否自己提出INPC?

如果您想更新在ViewModel要麼NameAge的價值並使其在視圖中反映,你需要他們提高物業內Person類單獨改變了。

綁定很好,但視圖幾乎沒有通知視圖模型的變化。還記得UpdateSourceTriggerTextBox默認爲LostFocus,設置爲PropertyChanged將更新您輸入的ViewModel中的字符串。

簡單的例子:

public class Person : INotifyPropertyChanged { 
    private string _name; 
    public string Name { 
    get { 
     return _name; 
    } 

    set { 
     if (value == _name) 
     return; 

     _name = value; 
     OnPropertyChanged(() => Name); 
    } 
    } 

    // Similarly for Age ... 
} 

現在你的XAML是:

<StackPanel DataContext="{Binding CurrentPerson}"> 
    <TextBox Text="{Binding Name}" /> 
    <TextBox Margin="15" 
      Text="{Binding Age}" /> 
</StackPanel> 

,或者您也可以通過綁定@Kshitij

的建議
<StackPanel> 
    <TextBox Text="{Binding CurrentPerson.Name}" /> 
    <TextBox Margin="15" 
      Text="{Binding CurrentPerson.Age}" /> 
</StackPanel> 

,並更新視圖模型你的打字

<StackPanel DataContext="{Binding CurrentPerson}"> 
    <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /> 
    <TextBox Margin="15" 
      Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" /> 
</StackPanel> 
+0

明白了,謝謝 – LastBye 2013-03-25 11:11:29

12

試試這個:

<TextBox Text="{Binding CurrentPerson.Name}" /> 
<TextBox Text="{Binding CurrentPerson.Age}" /> 

本質上講,你可以通過使用.分離器深入到性能。

以供將來參考,如果你想深入到集合,您可以使用MyCollection[x]就像你在代碼中(其中x會被硬編碼號碼代替,不是一個變量)。

+0

+1謝謝你的信息,不確定在Xaml部分我可以使用這個,但我想我也嘗試過這種方式。這種方法再次沒有結果,CurrentPerson定義並觸發NotifyPropertyChanged,但可能還有一些缺失。 – LastBye 2013-03-25 09:25:06

+0

似乎通知改變不會採取這種行動。這是真的嗎?我應該如何解決這個問題? – LastBye 2013-03-25 09:38:46

+0

還沒有爲我工作。不知道爲什麼... – LastBye 2013-03-25 10:00:35