为什么这个代码隐藏的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);
答案 0 :(得分: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);