1

我的 WPF 应用程序使用资源字典。我也在使用 MVVM。

我正在绑定到 ResourceDictionary,但想将我的 MainWindow ViewModel 绑定到 MainWindow(Window 类型),但 MVVM 不会让我作为 MainWindow,它不是 UserControl 类型。

   <Grid.Resources>
        <ResourceDictionary Source="Resources\ResourceDictionary.xaml" />
    </Grid.Resources>

    <Grid.DataContext>
        <Binding Source="{StaticResource Mwvm}" />
    </Grid.DataContext>
</Grid>

这意味着我不能这样做

<DataTemplate DataType="{x:Type viewModel:MainWindowViewModel}">
    <root:MainWindow x:Key="Mwvm" />
</DataTemplate>

有谁知道我可以如何做同样的事情,但是当对象是一个窗口并且只使用 XAML 时(我知道我可以使用 app.xaml onstartup() 中的代码来做到这一点)?

编辑 为了清楚地说明这一点,我知道在我的 MainWindow 中我可以向我的 ViewModel 声明一个命名空间,但是当我的 ResourceDictionary 中已经引用了命名空间并且我正在引用我的 ResourceDictionary 时,这是正确的方法吗?

4

1 回答 1

1

嗯怎么样?

<Window>
    <Window.DataContext>
        <someNs:YourVmClass /> <!-- calls the empty c_tor of the class-->
    </Window.DataContext>
</Window>

(我不确定,如果我理解你的问题。但我想,这就是你真正想要的。)

根据您的编辑:

当然你可以做类似的事情

<!-- Define an instance of your VM in the ResourceDictionary -->
<ResourceDictionary>
    <someNs:YourVmClass x:Key="InstOfYourVmClass" />
</ResourceDictionary>

在你看来,你可以做这样的事情。

<Grid>
    <Grid.Resources>
        <ResourceDictionary Source="Resources\ResourceDictionary.xaml" />
    </Grid.Resources>

    <Grid.DataContext>
        <StaticResource ResourceKey="InstOfYourVmClass" />
    </Grid.DataContext>
</Grid>

但我强烈建议不要选择这种方法。问题是,每次您引用它ResourceDictionary时,当前实例InstOfYourVmClass都会被新的实例化版本覆盖。

于 2013-06-05T14:10:52.903 回答