本文介绍了我应该为我的视图使用 UserControls 而不是 DataTemplates 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这篇文章,作者建议使用 DataTemplates 来定义ViewModel 是疯子的做法(#7).我经常这样做,真的有那么糟糕吗?

I was reading this post and the author makes the suggestion that using DataTemplates to define a ViewModel is a lunatic's way to do it (#7). I do that all the time, is it really that bad?

<DataTemplate DataType="{x:Type local:MyViewModel}">
    <Grid>
        ...
    </Grid>
</DataTemplate>

我的大多数视图只是一个定义一两个 DataTemplate 的 ResourceDictionary.对我来说,这样做比为每个 ViewModel 创建一个 UserControl 更有意义.为什么我不需要 WPF 的可视化树中的额外层?当 DataTemplate 为我做这件事时,为什么我要照顾将 ViewModels 映射到 Views?这种语法真的是疯子方法"吗?

Most of my Views are simply a ResourceDictionary that defines a DataTemplate or two. To me, it makes much better sense to do this than creating a UserControl for every ViewModel. Why would I want the extra layer in WPF's visual tree when it's not needed? And why would I want to take care of mapping ViewModels to Views when a DataTemplate does that for me? Is this syntax really a "lunatics approach"?

推荐答案

没有什么不好,除了非常大的 xaml 文件和 DataTemplates 在设计表面上缺乏编辑支持.

Nothing bad about it, except for incredibly large xaml files and the lack of edit support that DataTemplates have on the design surface.

如果这些问题正在伤害您,您可以随时...

If those issues are hurting you, you can always...

<DataTemplate DataType="{x:Type local:MyViewModel}">
    <local:MyViewModelUserControl />
</DataTemplate>

这篇关于我应该为我的视图使用 UserControls 而不是 DataTemplates 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 22:40