Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c# - How to fix listview checkbox behaviour?

I created Listbox with property checkboxes == true, but the problem that I had was that I was needed to click twice on the line in order to set it checked. I was needed to change it in such a way that I can click on the line just once and the line set as checked. What I did is added mouseClick event:

        private void Cbl_folders_MouseDown(object sender, MouseEventArgs e)
        {
            SelectedListViewItemCollection selectedItemsList = Cbl_folders.SelectedItems;

            if(selectedItemsList.Count > Constants.EMPTY_COUNT)
            {
                selectedItemsList[0].Checked = !selectedItemsList[0].Checked;
            }
        }

And everything works fine, first, click on the line set the line as checked the second click on the line set the line as unchecked. But then I found out that if you clicked on the line and set this line as checked and then you click on the checkbox on the other line, so your first line that was checked changes the state to unchecked. Why? Because I am tracking mouseDown event and even when I click on the checkbox on the other line mouse down event looks on selected items and the obviously selected item is the first line that was clicked.

I understand that it is possible to add some flags and look where was a click and so on, but it seems overcomplicated, I feel like there is should be a simpler solution.

question from:https://stackoverflow.com/questions/65902160/how-to-fix-listview-checkbox-behaviour

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Handle the MouseDown event to switch the ListViewItem.Checked property when you click over the label area. To get info about the clicked area, call the ListView.HitTest method which returns a ListViewHitTestInfo object and check the Location property, the property returns one of the ListViewHitTestLocations values.

private void Cbl_folders_MouseDown(object sender, MouseEventArgs e)
{
    if (Cbl_folders.CheckBoxes)
    {
        var ht = Cbl_folders.HitTest(e.Location);

        if (ht.Item != null && ht.Location == ListViewHitTestLocations.Label)
            ht.Item.Checked = !ht.Item.Checked;
    }
}

This way, the items are checked/unchecked by the mouse also when you click outside their check boxes areas (determined by the ListViewHitTestLocations.StateImage value).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...