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

查看:17
本文介绍了带有 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.

    我正在使用

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

  • 所以我有两个问题:

    1. 我是否正确地认为,如果在 XAML 中使用 UserControl,那么当控件的 Loaded 事件触发时,UserControl 必须将 ViewModel 设置为其 DataContext而不是使用 方法?

    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?

    推荐答案

    首先,我不认为 MVVM 是一个好的选择,如果您正在开发一个将被其他人使用的 UserControl.无外观控件才是您真正应该开发的控件.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天全站免登陆