Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

Is there something wrong limiting the DataContext to the ViewModel of the Window?

I don't feel comfortable letting any object being the DataContext of my views. As I'm following the MVVM pattern all windows have their own VM. What I plan to do is the following (taken from a window called Options):

    internal new OptionsVM DataContext
    {
        get
        {
            return (OptionsVM) base.DataContext;
        }
        set
        {
            if (this.DataContext != value)
            {
                base.DataContext = value;
            }
        }
    }

Do you see if I'm missing something or if this can be a bad idea due to something I'm not aware of?

Thanks in advance.

Upvotes: 2

Views: 304

Answers (3)

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31651

Your approach should pose no dangers - if it makes it easier for you, enforce it. Just make sure that you comment why you chose to implement it this way. I am all for stronger data-typing over the base Object class. I think this actually makes it clearer what the supported context is.

Even using a constructor approach as suggested by @SeanU will not prevent others from changing the DataContext type after creation.

Upvotes: 1

Sean U
Sean U

Reputation: 6850

In general, hiding interface elements can lead to odd bugs. For example, the following code will generate an InvalidCastException:

OptionsView view = new OptionsView();
Window window = view;
window.DataContext = new DifferentVM();
OptionsVM = view.DataContext;

It's a somewhat contrived example, but if you ever use WPF bindings to set an object's DataContext then similar scenarios are very likely.

I find it preferable to let the DataContext property exist as it was designed, and instead give my Views a constructor which accepts a data context in a more strongly-typed fashion. In the View's code I also have a ViewModel property of the appropriate type:

public OptionsView(OptionsVM viewModel)
{
    DataContext = viewModel;
}

private OptionsVM ViewModel { get { return DataContext as OptionsVM; } }

Upvotes: 2

Richard Blewett
Richard Blewett

Reputation: 6109

The only issue I can see is if you use the construct

Window view = new OptionsView();

view.DataContext = ....;

then the DataContext will still be of type object - it requires you to always use a reference of the type of the view to see your strong typing

Upvotes: 2

Related Questions