我应该为我的视图使用 UserControls 而不是 DataTemplates 吗?
我正在阅读这篇文章,作者提出使用 DataTemplates 定义 ViewModel 的建议这是一个疯子的做法(#7)。我经常这样做,真的有那么糟糕吗?
<DataTemplate DataType="{x:Type local:MyViewModel}">
<Grid>
...
</Grid>
</DataTemplate>
我的大多数视图只是一个定义一两个 DataTemplate 的 ResourceDictionary。对我来说,这样做比为每个 ViewModel 创建一个 UserControl 更有意义。当不需要 WPF 可视化树时,为什么我需要额外的层?当 DataTemplate 为我做这件事时,为什么我要负责将 ViewModel 映射到视图呢?这种语法真的是“疯狂的方法”吗?
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>
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了令人难以置信的大 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 的好处是它们是 Viewmodel 类的强类型。您需要做的就是在 View 中创建一个 ContentPresenter 并将 DataContext 绑定到 VM。如果您的 DataTemplate 是在 ResourceDictionary 中定义的,并且具有 DataType 属性而不是 Key,则 WPF 将在内部找出 VM 类的正确 DataTemplate 并显示它。
但正如您所提到的,我们无法在单独的文件中创建 DataTemplate。因此,ResourceDictionary 中存在 DataTemplates 的文件(例如 App.xaml),该文件变得非常混乱,并且很快就变得难以管理代码。
所以我的看法是,如果虚拟机很简单,则创建一个数据模板。否则,最好创建一个单独的 UserControl 并将其内容绑定到 VM。
The good thing with DataTemplate is that they are strongly typed to Viewmodel classes. All you need to do is create a ContentPresenter in View and Bind DataContext to VM. If your DataTemplate is defined in a ResourceDictionary and has a DataType attribute instead of Key, WPF will internally figure out the right DataTemplate for the VM class and display it.
But as you mentioned, we cannot create the DataTemplate in a seperate file. So the file where the DataTemplates exist in ResourceDictionary (e.g. App.xaml), the file gets really messy and it becomes difficult to manage the code soon.
So my take is, if the VM is simple create a DataTemplate. Or else it is always better to create a seperate UserControl and bind its content to the VM.
我遇到了性能问题。接下来两种情况之间存在差异:
1.
2.
在第一种情况下,渲染结果所需的时间比第二种情况更长。而这个差异大约在2倍左右。
我将其作为单独的问题发布
I run into the issue with performance. There is difference between next two case:
1.
2.
In 1st case it takes longer to render results than in the 2nd. And this difference is in about 2 times.
I posted it as a separate question