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.
It is not possible to reference the static resource, if it is defined later in the xaml file. Therefore, you could do the following:
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.