具有MVVM和依赖项属性的WPF用户控件地狱

编程入门 行业动态 更新时间:2024-10-11 15:16:57
本文介绍了具有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>

  • 所以我有两个问题:

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

  • 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用户控件地狱

    本文发布于:2023-11-09 21:18:46,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1573464.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:控件   属性   地狱   用户   MVVM

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!