Reputation: 746
I like ReactiveUI's code-based binding mechanisms. However, there are times when you need to use XAML bindings. In these cases, the DataContext needs to be set up properly between the View and ViewModel. I’ve been doing this in the View constructor:
public MyView()
{
InitializeComponent();
this.WhenActivated(disposables =>
{
this.DataContext = this.ViewModel;
...
});
}
This works, but I get errors in the output window at runtime:
System.Windows.Data Error: 40 : BindingExpression path error: ...
I'm using ReactiveUserControls, ViewModelViewHosts, and registering the View/ViewModel mappings in the Locator and letting ReactiveUI resolve them. I think I'm setting the DataContext as early as I can. So when I need to use XAML bindings - is there an alternative way of setting up the DataContext to avoid the phantom debug output errors?
Upvotes: 4
Views: 324
Reputation: 2888
The issue with what you have is you'll never adaptively get new versions of the ViewModel and you might get delayed subscriptions.
You are better off considering using the WhenAnyValue() operator eg:
this.WhenAnyValue(x => x.ViewModel).Bindto(this, x => x.DataContext);
Consider still playing it inside your WhenActivated() since that will avoid memory leaks, otherwise keep a reference to the IDisposable and disposing when your View has been closed.
Upvotes: 3