Shane
Shane

Reputation: 2351

Is binding to a ViewModel property instead of using DataContext a valid way to connect a ViewModel to view?

Most of the stuff I read about MVVM in WPF talks about connecting the view to the view model by somehow setting the DataContext of the view to an instance of the view model. I don't like using DataContext as it's not typed, and therefore intellisense doesn't work.

I am thinking of using an approach where the view has a property called ViewModel which is set to an instance of the property. Since this property has specific type, I can bind to a property of the view model like this

<TextBlock Text="{Binding Path=ViewModel.Property1, ElementName=_viewWindow}"/>

where _viewWindow is the name applied to view class (which could be a Window or UserControl for example). Whilst this is a bit more verbose than binding via DataContext it has the advantage that intellisense will work.

The view model will implement INotifyPropertyChanged.

Is this a valid approach? I haven't seen any references to the approach in anything I have read about MVVM but it seems like a reasonable idea.

Are there other advantages to using DataContext that I am missing apart from shorter binding syntax?

One thing I did see in another answer was adding a property that casts DataContext to the view model type.

Upvotes: 0

Views: 387

Answers (1)

iajs
iajs

Reputation: 71

If you set your data context via XAML your intellisense will work.

<Window 
...>
<Window.DataContext>
    <MyViewModel />
</Window.DataContext>

If you don't like coupling your view to a specific implementation, you can actually use an interface for the view model:

<Window
...>
<Window.DataContext>
    <x:Type Type="IMyViewModel" />
</Window.DataContext>

You would then need to set the DataContext via the code behind.

public class MyView
{
    public MyView(IMyViewModel myViewModel)
    {
        this.DataContext = myViewModel;
    }
}

Upvotes: 2

Related Questions