1

为什么这个代码隐藏 DataBinding 不起作用,当我在 XAML 中做同样的事情时它工作正常。

 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);
4

1 回答 1

6

您只设置了SourceBinding 的,但没有设置它的Path. 声明应如下所示,使用mainWindowViewModel实例 as 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);
于 2013-08-05T10:45:11.287 回答