简体   繁体   中英

Get the value of selected checkboxes in an array - WPF, MVVC, c#

Hi I am am working on an application that has MVVC framework.

On my view I have 23 checkboxes each with a different text.

<CheckBox IsChecked="{Binding isA}">A</CheckBox>
<CheckBox IsChecked="{Binding isB}">B</CheckBox>
<CheckBox IsChecked="{Binding isC}">C</CheckBox>    

and so on.

in viewmodal I have the following....

public string isA
    {
        get { return _isA; }
        set
        {
            _isA= value.ToString();
            RaisePropertyChanged();
        }
    }
    private string _isA;

How do I get all the selected checkboxes text as an array?

Start by defining a model class

public class ListModel
 {
     public string Data { get; set; }
     public bool IsSelected { get; set; }
 }

Then Bind the list of this model to the Listview's ItemsSource

List<ListModel> data = new List<ListModel>();

modify the binding of your check box to

 <CheckBox Content="{Binding Data}" IsChecked="{Binding Path=IsSelected, Mode=TwoWay"/>

then when you need to retrieve you may execute the following linq to get all selected strings

IEnumerable<String> selectedData = data.Where(d => d.IsSelected).Select(d => d.Data);

now you'll have all the data which is selected in the UI in the field selectedData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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