简体   繁体   中英

WPF Code-behind DataBinding Not Working

Why is this code-behind DataBinding not working, when I do the same thing in XAML it is working fine.

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

You have only set the Source of the Binding, but not its Path . The declaration should look like this, using the mainWindowViewModel instance 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);

or shorter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM