博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(WPF) MVVM: 动态添加控件及绑定。
阅读量:4703 次
发布时间:2019-06-10

本文共 2301 字,大约阅读时间需要 7 分钟。

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

 

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

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

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

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

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

ViewModel

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

 

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

View

于是,并不用在后台写过多的代码,修改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
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.

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

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里面引用:

 

转载于:https://www.cnblogs.com/fdyang/p/3877309.html

你可能感兴趣的文章
开地址哈希表(Hash Table)的原理描述与冲突解决
查看>>
tomcat启动错误org.springframework.beans.factory.CannotLoadBeanClassException的解决
查看>>
在Ubuntu中安装配置java后运行java -version时提示二进制文件不能执行
查看>>
太原中软教你Java入门
查看>>
解决数据库卡死问题
查看>>
JavaScript数据类型之null和undeined
查看>>
文件首行为空白行,为什么该行字符串长度为1(line.length()=1)
查看>>
ES5初尝试Object.create
查看>>
NTP校时设置
查看>>
Perl 面对对象的案例理解
查看>>
两数组比较,筛选出不同元素(附数组去重)
查看>>
IOS学习之路十九(JSON与Arrays 或者 Dictionaries相互转换)
查看>>
多线程简单实例(2)生产者和消费者
查看>>
Git在合并时遇到unrelated history提示时无法merge
查看>>
全自动ARP实时绑定BAT文件
查看>>
如何将.class文件反编译为.java文件
查看>>
POJ 1154 LETTERS dfs
查看>>
poj 3009 Curling 2.0(dfs)
查看>>
新浪微博客户端(10)-切换多个fragment
查看>>
新浪微博客户端(12)-判断当前软件是否是新版本(是否显示新特性)
查看>>