比如需要显示一个键盘,里面有各个按键。实现的效果如下:

之前的思路,就是建立一个singleKey的控件,然后在后台用代码动态的添加到父控件里去, 再用代码在后台进行绑定。

这种实现方法并不是真正的MVVM的模式。体会不到MVVM带来的便捷和惊喜。

用MVVM模式来实现时的思路如下:

1. 建立singleKey的ViewModel,定义需要绑定View的属性。

2. 在Key的ViewModel中,使用可观察集合,并绑定到View的ItemsSource上。

ViewModel

        public ObservableCollection<DutSingleKeyViewModel> Keysets
{
get
{
return this.keysets;
}
set
{
this.keysets = value;
}
}

3. 对于singleKey的显示,可以在DataTemplat里面定义。

View

    <UserControl.DataContext>
<vm:DutKeysetViewModel />
</UserControl.DataContext>

<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:DutSingleKeyViewModel}">
<Canvas>
<Grid Canvas.Left="{Binding KeyLocationLeft, Mode=OneWay}"
Canvas.Top="{Binding KeyLocationTop, Mode=OneWay}"
>
<Rectangle Fill="#FFF4F4F5"
HorizontalAlignment="Left"
Width="{Binding KeySizeWidth}"
Height="{Binding KeySizeHeight}"

Stroke="Black"
VerticalAlignment="Top"></Rectangle>
<TextBlock HorizontalAlignment="Left"
TextWrapping="Wrap"
Text="{Binding KeyCharacter}"
Margin="5,0,0,0"
VerticalAlignment="Top" />
</Grid>
</Canvas>
</DataTemplate>
</UserControl.Resources>
<Grid>
<WrapPanel HorizontalAlignment="Left"
Height="227"
Width="532">
<ItemsControl ItemsSource="{Binding Keysets}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</WrapPanel>

于是,并不用在后台写过多的代码,修改ViewModel后, View的显示就相应变更了。

补充网上大牛的回复。

if you really want to do mvvm , try to forget "how can i add controls". you dont have to, just think about your viewmodels - WPF create the contols for you :)

in your case lets say we have a SearchViewModel and a SearchEntryViewmodel.

public class SearchEntryViewmodel
{
//Properties for Binding to Combobox and Textbox goes here
} public class SearchViewModel
{
public ObservableCollection<SearchEntryViewmodel> MySearchItems {get;set;}
public ICommand AddSearchItem {get;}
}

till now you dont have to think about usercontrols/view. in your SearchView you create an ItemsControl and bind the ItemsSource to MySearchItems.

<ItemsControl ItemsSource="{Binding MySearchItems}"/>

you see now all of your SearchEntryViewmodels in the ItemsControl(just the ToString() atm).

To fit your requirements to show every SearchEntryViewmodel with 3Comboboxes and so on you just have to define a DataTemplate in your Resources

<DataTemplate DataType="{x:Type local:SearchEntryViewmodel}">
<StackPanel Orientation="Horizontal">
<Combobox ItemsSource="{Binding MyPropertyInSearchEntryViewmodel}"/>
<!-- the other controls with bindings -->
</StackPanel>
</DataTemplate>

thats all :) and you never has to think about how can i add controls dynamically. you just have to add new SearchEntryViewmodel to your collection.

this approach is called Viewmodel First and i think its the easiest way to do MVVM.

在实践发现,通用的方法还是创建一个userControl view,重要的是再DataTemplate里面引用:

    <Window.Resources>
<DataTemplate DataType={x:Type viewmodels:MyUserControlViewModel}">
<views:MyUserControlView />
</DataTemplate>
</Window.Resources>

(WPF) MVVM: 动态添加控件及绑定。的更多相关文章

  1. C# WPF后台动态添加控件(经典)

    概述 在Winform中从后台添加控件相对比较容易,但是在WPF中,我们知道界面是通过XAML编写的,如何把后台写好的控件动态添加到前台呢?本节举例介绍这个问题. 这里要用到UniformGrid布局 ...

  2. WPF 动态添加控件以及样式字典的引用(Style introduction)

    原文:WPF 动态添加控件以及样式字典的引用(Style introduction) 我们想要达到的结果是,绑定多个Checkbox然后我们还可以获取它是否被选中,其实很简单,我们只要找到那几个关键的 ...

  3. WPF:理解ContentControl——动态添加控件和查找控件

    WPF:理解ContentControl--动态添加控件和查找控件 我认为WPF的核心改变之一就是控件模型发生了重要的变化,大的方面说,现在窗口中的控件(大部分)都没有独立的Hwnd了.而且控件可以通 ...

  4. JQuery动态添加控件并取值

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  5. winform导入导出excel,后台动态添加控件

    思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...

  6. Android 在布局容器中动态添加控件

    这里,通过一个小demo,就可以掌握在布局容器中动态添加控件,以动态添加Button控件为例,添加其他控件同样道理. 1.addView 添加控件到布局容器 2.removeView 在布局容器中删掉 ...

  7. VC中动态添加控件

    VC中动态添加控件 动态控件是指在需要时由Create()创建的控件,这与预先在对话框中放置的控件是不同的. 一.创建动态控件: 为了对照,我们先来看一下静态控件的创建. 放置静态控件时必须先建立一个 ...

  8. jQuery EasyUI动态添加控件或者ajax加载页面后不能自动渲染问题的解决方法

    博客分类: jquery-easyui jQueryAjax框架HTML  现象: AJAX返回的html无法做到自动渲染为EasyUI的样式.比如:class="easyui-layout ...

  9. asp.net动态添加控件学习

    看了老师的教程后,自己一点感悟记录下来: 1.在页面提交后,动态生成的控件会丢失, 但如果生成控件的代码在pageload中,就可以,原理是每次生成页面都执行生成. 2.动态按件或页面原来控件, 在页 ...

随机推荐

  1. SpringSecurity相关配置【SpringSecurityConfig】

    SpringSecurity的配置相对来说有些复杂,如果是完整的bean配置,则需要配置大量的bean,所以xml配置时使用了命名空间来简化配置,同样,spring为我们提供了一个抽象类WebSecu ...

  2. tyvj1018 - 阶乘统计 ——暴力

    题目链接:https://www.tyvj.cn/Problem_Show.aspx?id=1018 范围只有20,在long long Int范围内. #include <cstdio> ...

  3. jQuery中的ajax服务端返回方式详细说明

    http://blog.sina.com.cn/s/blog_6f92e3a70100u3b6.html     上次总结了下ajax的所有参数项,其中有一项dataType是设置具体的服务器返回方式 ...

  4. spring-mvc不拦截静态资源的配置

    spring-mvc不拦截静态资源的配置 标签: spring 2015-03-27 23:54 11587人阅读 评论(0) 收藏 举报 版权声明:本文为博主原创文章,未经博主允许不得转载. &qu ...

  5. JavaWeb学习记录(十九)——jstl自定义标签库之传统标签

    一.传统标签 (1)JSP引擎将遇到自定义标签时,首先创建标签处理器类的实例对象,然后按照JSP规范定义的通信规则依次调用它的方法. public void setPageContext(PageCo ...

  6. pthread_join和pthread_detach的用法(转)

    一:关于join join join是三种同步线程的方式之一.另外两种分别是互斥锁(mutex)和条件变量(condition variable). 调用pthread_join()将阻塞自己,一直到 ...

  7. Linux 安装rar解压工具

    下载RAR安装包: http://www.rarsoft.com/download.htm 我的是CentOS 64位: wget http://www.rarsoft.com/rar/rarlinu ...

  8. 内存使用空间之swap建置[转]

    http://www.cnblogs.com/ggjucheng/archive/2012/08/22/2651502.html 内存置换空间(swap)之建置 安装时一定需要的两个 partitio ...

  9. 【转】iOS基于WebSocket的聊天机制

    原文网址:http://www.jianshu.com/p/21d9b3b94cfc WebSocket 的使得浏览器提供对 Socket 的支持成为可能,从而在浏览器和服务器之间提供了一个基于 TC ...

  10. linux下Redis与phpredis扩展安装

    ++++++++++++++++++++++++++++++++++++++++++++++linux下Redis与phpredis扩展安装++++++++++++++++++++++++++++++ ...