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

之前的思路,就是建立一个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. ubuntu 双屏问题的解决方案

    ubuntu有一个很让人头疼的问题就是它默认开启双屏.只要你有两个显示器接口,即使你没有两块屏幕,它也是按照双屏幕去显示. 这就会造成一些很让人无语的问题,比如,恰好跳到你没有的那个屏幕就可能导致无法 ...

  2. 软件或jar包等名字里的GA意思

    首页 > 转贴的文章 > 软件的版本"GA"代表什么意思?如MyEclipse 5.0 GA   软件的版本"GA"代表什么意思?如MyEclips ...

  3. leetcode 108 Convert Sorted Array to Binary Search Tree ----- java

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 给一 ...

  4. UVa 1339 Ancient Cipher --- 水题

    UVa 1339 题目大意:给定两个长度相同且不超过100个字符的字符串,判断能否把其中一个字符串重排后,然后对26个字母一一做一个映射,使得两个字符串相同 解题思路:字母可以重排,那么次序便不重要, ...

  5. kuangbin_ShortPath G (POJ 1502)

    尽管题目很长 写的很玄乎 让我理解了半天 但是事实上就是个模板题啊摔 一发水过不解释 #include <iostream> #include <string> #includ ...

  6. js的数组操作 splice

    原文:点击打开链接 1.作用:从指定位置删除部分元素并增加新的元素                1.1.该方法返回值是被删除的元素组成的数组                1.2.splice是直接 ...

  7. (转)The 9 Deep Learning Papers You Need To Know About (Understanding CNNs Part 3)

    Adit Deshpande CS Undergrad at UCLA ('19) Blog About The 9 Deep Learning Papers You Need To Know Abo ...

  8. 10046事件跟踪会话sql

    背景知识: 10046 事件按照收集信息内容,可以分成4个级别: Level 1: 等同于SQL_TRACE 的功能 Level 4: 在Level 1的基础上增加收集绑定变量的信息 Level 8: ...

  9. node.js BootStrap安装

    最近想用Bootstrap开发项目,以便使用其丰富的资源: 捯饬了一下nodejs的安装和配置:windows下弄起来还是比较狗屎的,两三天下班时间才弄好: http://xiaoyaojones.b ...

  10. “锁定”语句 lock(C# 参考)

    此文章由人工翻译. 将光标移到文章的句子上,以查看原文. 更多信息. 译文 原文 "锁定"语句(C# 参考) 其他版本 <?XML:NAMESPACE PREFIX = &q ...