具有MVVM和依赖项属性的WPF用户控件地狱 [英] WPF User Control hell with MVVM and Dependency Properties

查看:195
本文介绍了具有MVVM和依赖项属性的WPF用户控件地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的:

  • 我正在写一个我想被其他开发人员使用的UserControl.
  • 我希望最终用户能够通过依赖项属性"使用我的控件.

  • I'm writing a UserControl that I want to be consumed by other developers.
  • I want end users to be able to use my control using Dependency Properties.

<lib:ControlView ControlsText={Binding Path=UsersOwnViewModelText} />

  • 我正在使用MVVM模式.

  • I'm using the MVVM pattern.

    我正在使用<DataTemplates>

    <DataTemplate DataType="{x:Type local:ControlViewModel}">  
        <local:ControlView />  
    </DataTemplate>
    

  • 所以我有两个问题:

    1. 我是在想,如果在XAML中使用了UserControl,则当控件的Loaded事件触发时,UserControl必须将ViewModel设置为其DataContext,而不是使用<DataTemplate>方法?

    1. Am I right in thinking that if a UserControl is being consumed in XAML then the UserControl must set the ViewModel as its DataContext when the control's Loaded event fires instead of using the <DataTemplate> method?

    如何允许用户将数据绑定到控件的依赖项属性,同时仍将数据绑定到ViewModel?

    How do I allow users to data bind to my control's dependency properties while still being data bound to my ViewModel?

    推荐答案

    首先,如果您正在开发将由其他用户使用的UserControl,我认为MVVM不是一个不错的选择.一个无表情的控件是您真正应该开发的.耶利米·莫里尔(Jeremiah Morrill)具有

    First off, I don't think MVVM is a good choice if you are developing a UserControl that will be consumed by others. A lookless control is what you really should be developing. Jeremiah Morrill has a blog post about this subject.

    话虽如此,如果您具有默认的公共构造函数,则可以使用XAML设置数据上下文.

    With that said, you can set the datacontext with XAML if you have a default public constructor.

    在ControlView.xaml内部放置:

    Inside ControlView.xaml put:

    <UserControl.DataContext>
        <local:ControlViewModel />
    </UserControl.DataContext>
    

    这篇关于具有MVVM和依赖项属性的WPF用户控件地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆