mvvm绑定checkbox wpf_(WPF) MVVM: 动态添加控件及绑定。

本文介绍了如何在WPF中使用MVVM模式动态添加Checkbox控件并进行数据绑定。通过创建ViewModel,使用ObservableCollection绑定到View的ItemsSource,避免了后台代码的直接操作,实现了MVVM的便捷。DataTemplate用于定义单个Checkbox的显示方式,实现了视图的自动更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

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

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

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

ViewModel

public ObservableCollectionKeysets

{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.

publicclassSearchEntryViewmodel{//Properties for Binding to Combobox and Textbox goes here}publicclassSearchViewModel{publicObservableCollectionMySearchItems{get;set;}publicICommandAddSearchItem{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里面引用:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值