Should I be using UserControls for my Views instea

2019-02-08 17:49发布

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"?

3条回答
该账号已被封号
2楼-- · 2019-02-08 18:34

I run into the issue with performance. There is difference between next two case:

1.

<DataTemplate DataType="{x:Type local:MyViewModel}">
    <!-- xaml is moved to separate user control -->
    <local:MyViewModelUserControl />
</DataTemplate>

2.

<DataTemplate DataType="{x:Type local:MyViewModel}">
    <!-- xaml is typed here directly -->
    <Border>
         ...
    </Border>
</DataTemplate>

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

查看更多
混吃等死
3楼-- · 2019-02-08 18:50

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>
查看更多
在下西门庆
4楼-- · 2019-02-08 18:55

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.

查看更多
登录 后发表回答