为什么此代码隐藏的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);

最佳答案

您仅设置了绑定的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);

关于c# - WPF代码隐藏数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18055649/

10-12 13:28