wpf 使用 StaticResource 设置 DataContext
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13333922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting DataContext using StaticResource
提问by Lucifer
I am trying to set the ViewModel as the DataContext of the View using the following XAML code:
我正在尝试使用以下 XAML 代码将 ViewModel 设置为 View 的 DataContext:
<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:
但是,我观察到视图模型构造函数被调用了两次。我知道视图模型在 XAML 中被实例化了两次,我应该将 DataContext 设置为资源中的静态资源。但是,我无法弄清楚如何使用 StaticResource 设置 DataContext。我尝试了以下但它给出了一个例外:
<UserControl .... DataContext="{StaticResource myViewModel}" >
Please help me figuring out what should be the appropriate XAML code for assigning the DataContext.
请帮助我找出用于分配 DataContext 的适当 XAML 代码。
回答by Nico Schertler
It is not possible to reference the static resource, if it is defined later in the xaml file. Therefore, you could do the following:
如果稍后在 xaml 文件中定义了静态资源,则无法引用该静态资源。因此,您可以执行以下操作:
<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.
我想知道您为什么要将 ViewModel 定义为静态资源。就个人而言,我更喜欢在DataContext.

