1

I am trying to set the ViewModel as the DataContext of the View using the following XAML code:

<UserControl.DataContext>
    <local:MyViewModel />
</UserControl.DataContext>

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/MA_Resources/MA_ResourceDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>

        <local:MyViewModel x:Key="myViewModel" x:Name="myVM" />
    </ResourceDictionary>
</UserControl.Resources>

But, I observe that the view-model constructor is called twice. I understand the the view-model is getting instantiated twice in XAML and that I should set the DataContext as the StaticResource from the Resources. However, I am not able to figure out how to set the DataContext with the StaticResource. I tried the following but it's giving an exception:

<UserControl .... DataContext="{StaticResource myViewModel}" >

Please help me figuring out what should be the appropriate XAML code for assigning the DataContext.

1 Answer 1

3

It is not possible to reference the static resource, if it is defined later in the xaml file. Therefore, you could do the following:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/MA_Resources/MA_ResourceDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>

        <local:MyViewModel x:Key="myViewModel" x:Name="myVM" />
    </ResourceDictionary>
</UserControl.Resources>
<UserControl.DataContext>
    <StaticResourceExtension ResourceKey="myViewModel"/>
</UserControl.DataContext>

I wonder why you want do define the ViewModel as a static resource. Personally, I would prefer the instantiation in the setter of the DataContext.

Sign up to request clarification or add additional context in comments.

2 Comments

The problem is if you are binding a property to something that doesn't inherit datacontext (i.e. DataGridColumn's Visibility property), then it makes it a heck of a lot easier to do the binding with a source={StaticResource VM}.
For d:DataContext, use: d:UserControl.DataContext

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.