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

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

之前的思路,就是建立一个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里面引用:

相关资源:WPFcheckbox使用
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页

打赏

苗华栋

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者