简体   繁体   English

WPF-将数据从数据库绑定到复选框控件的最佳方法是什么

[英]WPF - what is the best way to bind data from a database to a checkbox control

I am struggling some time with checkbox control in WPF. 我正在花一些时间在WPF中使用复选框控件。 What I am trying is to to make some kind of filter. 我正在尝试制作某种过滤器。 1. So first I need to fill the checkbox control with the database items 2. Second I need to check if anything is checked 3. Third if anything is checked I want to take those values and use them to search through the database 4. Should I use only checkbox control for this or should I put it in some container or a listBox? 1.因此,首先,我需要用数据库项填充复选框控件。2.其次,我需要检查是否检查了任何内容。3.接下来,如果要检查任何内容,我想获取这些值并使用它们来搜索数据库。4.应该我只为此使用复选框控件,还是应该将其放在某个容器或listBox中?

I have find many topics here that are mentioning this stuff, but I couldn't manage to find the complete answer, only lot of parts that are not compatible with each other. 我在这里找到了很多提到这些内容的主题,但是我无法找到完整的答案,只能找到彼此不兼容的许多部分。 I would really appreciate if someone explain to me how checkbox in WPF works. 如果有人向我解释WPF中的复选框如何工作,我将不胜感激。

If you have multiple values and you want to display multiple CheckBoxes, one for each of them, then you will need to use a ListBox and have the TemplateItem a CheckBox. 如果您有多个值,并且想要显示多个CheckBox,每个值对应一个,那么您将需要使用ListBox,并将TemplateItem设为CheckBox。 This way your collection of items is bound to the ListBox, and for each item in the ListBox a CheckBox is shown. 这样,您的项目集合将绑定到ListBox,并为ListBox中的每个项目显示一个CheckBox。

So to get each of the values after there is an additional step if your doing MVVM and don't want to touch the UI. 因此,如果您要执行MVVM并且不想触摸UI,则需要执行一个附加步骤才能获得每个值。 What you do is create a wrapper class that sits around your class and has a extra property for the IsChecked data. 您要做的是创建一个包装类,该包装类位于您的类周围,并具有IsChecked数据的额外属性。 This way you can get the checked state without touching the UI. 这样,您无需触摸UI即可获得检查状态。

I have an example of this on my blog: Checked ListBox in WPF 我的博客上有一个示例: WPF中的Checked ListBox

To check which items are checked you just need a simple LINQ query. 要检查要检查的项目,您只需要一个简单的LINQ查询。 So if you use the example there from my blog then you should be able to do something like this: 因此,如果您使用我博客中的示例,那么您应该可以执行以下操作:

var checkedCustomers = Customers.Where(w=>w.IsChecked).ToList(); varcheckedCustomers = Customers.Where(w => w.IsChecked).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM