mercredi 2 décembre 2015

Getting the content of a checkbox within and Items Collection within a ListBox with wpf C#

I am pretty new to C#, I've been having this problem for a little while now. I have a ListBox named "listBox" which is bound to an Items Collection which has over 100 checkbox, each with a different content (or checkbox label).

I am trying to loop through each checkbox, and if it is checked, print the content into the console. I am able to detect if something is checked or not, however is definitely NOT the most efficient way of doing it. See my code below:

private void SomeButton_Click(object sender, RoutedEventArgs e)
    {
        string checkState = "";
        for (int i = 0; i < listBox.Items.Count - 1; i++)
        {
            checkState = listBox.Items[i].ToString().Substring(listBox.Items[i].ToString().Length - 5, 5);
            if (checkState != "False")
            {
                Console.WriteLine("Item " + i + " is checked");
            }
        }
    }

This code does work for detecting if something is checked or not properly. However it'd be more efficient if I was able to get the actual true/false property from the checkboxes in the ItemsCollection. I have tried numerous ways to attempt to get the checked state, as well as the checkbox content, but sadly I am coming up dry in every attempt. Here are a few of the things I have tried to get the content from one of these checkboxes:

Console.WriteLine(listBox.Items[i].ToString());

Console.WriteLine(listBox.Items.GetItemAt(i).ToString());

Console.WriteLine(listBox.Items.GetItemAt(i).Equals(0).ToString());

Any help would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire