【问题标题】:How to bind to type Window as a DataTemplate如何绑定到类型 Window 作为 DataTemplate
【发布时间】:2013-06-05 13:37:58
【问题描述】:

我的 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 时,这是正确的方法吗?

【问题讨论】:

    标签: wpf mvvm resourcedictionary


    【解决方案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 都会被新的实例化版本覆盖。

    【讨论】:

    • 这非常接近,但是,这将涉及我在我的 MainWindow 中声明命名空间。我可以使用在 ResourceDictionary 中声明的命名空间而不是定义两次(一次在我的 ResourceDictionary 中,一次在我的 MainWindow 中)来执行此操作!我的问题不清楚,现在更新。 +1
    猜你喜欢
    • 2013-02-08
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2010-12-29
    • 2013-07-15
    相关资源
    最近更新 更多