gpt4 book ai didi

wpf - 如何绑定(bind)到类型 Window 作为 DataTemplate

转载 作者:行者123 更新时间:2023-12-03 10:38:05 25 4
gpt4 key购买 nike

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

我正在绑定(bind)到 ResourceDictionary,但想将我的 MainWindow ViewModel 绑定(bind)到 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 时,这是正确的方法吗?

最佳答案

嗯怎么样?

<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将被新的实例化版本覆盖。

关于wpf - 如何绑定(bind)到类型 Window 作为 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com