2013-08-05 62 views
1

爲什麼此代碼隱藏DataBinding無法正常工作,當我在XAML中執行相同的操作時,它工作正常。WPF代碼隱藏DataBinding不工作

Binding frameBinding = new Binding(); 
frameBinding.Source = mainWindowViewModel.PageName; 
frameBinding.Converter = this; // of type IValueConverter 
frameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
frameBinding.IsAsync = true; 
frame.SetBinding(Frame.ContentProperty, frameBinding); 
+0

綁定成功。當設置PageName屬性時,也會調用Property changed通知。但在此之後,它沒有得到更新。 –

回答

6

你只設置綁定的Source,而不是它的Path。聲明應該是這樣的,使用mainWindowViewModel實例作爲Source

Binding frameBinding = new Binding(); 
frameBinding.Path = new PropertyPath("PageName"); // here 
frameBinding.Source = mainWindowViewModel; // and here 
frameBinding.Converter = this; 
frameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
frameBinding.IsAsync = true; 
frame.SetBinding(Frame.ContentProperty, frameBinding); 

或更短:

Binding frameBinding = new Binding 
{ 
    Path = new PropertyPath("PageName"), 
    Source = mainWindowViewModel, 
    Converter = this, 
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, 
    IsAsync = true 
}; 
frame.SetBinding(Frame.ContentProperty, frameBinding); 
+0

這也是**不**工作: frameBinding.Path = new PropertyPath(「。」); frameBinding.Source = mainWindowViewModel.PageName; –