WPF代码隐藏数据绑定不起作用

时间:2013-08-05 10:13:52

标签: c# wpf xaml data-binding

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

1 个答案:

答案 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);