Vasanth Sriram
Vasanth Sriram

Reputation: 1315

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

Upvotes: 1

Views: 3452

Answers (1)

Clemens
Clemens

Reputation: 128147

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

Upvotes: 6

Related Questions