我正在創建一個應用程序,它的作用類似於某些Microsoft應用程序的「嚮導」組件。爲了表示這一點,我有兩個的ViewModels:以編程方式綁定到不斷變化的ViewModel
class WizardVm {
public string Name { get; set; }
public ICommand QuitCommand { get { /* ommitted */ } }
public WizardStepVm CurrentStep { get; set; }
}
class WizardStepVm {
public string StepName { get; set; }
public string StepText {get; set; }
}
在視圖中,WizardVm
結合到窗口,並且WizardStepVm
結合到窗口內的內容面板。我編程創建內容控制,並將其添加到WizardView這樣的:
// in the "DataContextChanged" handler for the WizardView
var bn = new Binding("CurrentStep");
bn.Mode = BindingMode.OneWay;
var contentControl = new ContentControl();
contentControl.SetBinding(ContentControl.ContentProperty, bn);
WizardViewStackPanel.Children.Add(contentControl);
這個正確呈現最初創建時WizardView。但是,如果CurrentStep
發生更改,則視圖不會更新以反映此情況。 CurrentStep更改,但ContentControl繼續顯示原始WizardStepVm。此外,舊的WizardStepVm在內存中仍然存在,並且其字符串屬性仍然可以更改(從視圖中)。
這是爲什麼?我必須做些什麼才能使內容控件更改以反映ViewModel中綁定的更改?
(這裏實際上是對編程這樣一個很好的理由。然而,XAML解決方案也很受青睞。)
擺脫「//在」WizardView的「DataContextChanged」處理程序「。 MVVM – blindmeis