c# - 如何动态更改/设置 checkedListBox 项目前颜色

标签 c# winforms checkedlistbox

我有下面的代码。如何根据项目是否选中来设置 checkedListBox 项目的前景色?

private void FindSelectedUserRoles()
{
        lblSelectedUser.Text = Code.CommonUtilities.getDgvStringColValue(dataGridViewUserList, "UserName").Trim();

        //iterate all roles selected user is member of
        for (int i = 0; i < checkedListRoles.Items.Count; i++)
        {
            string roleName = checkedListRoles.Items[i].ToString();
            string selectedUserRoles = Code.MemberShipManager.GetSpecificUsersRoles(lblSelectedUser.Text.Trim());

            if (selectedUserRoles.Contains(roleName))
            {
                checkedListRoles.SetItemChecked(i, true);
                //here i want to set item fore colour to green

            }
            else if (selectedUserRoles.Contains(roleName) == false)
            {
                checkedListRoles.SetItemChecked(i, false);
                //and here, i want item fore colour to remain black
            }
        }
}

最佳答案

由于自己绘制东西相当复杂,实际上您可以让原始控件自行绘制——只需调整颜色即可。这是我的建议:

public class CustomCheckedListBox : CheckedListBox
{
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        Color foreColor;
        if (e.Index >= 0)
        {
            foreColor = GetItemChecked(e.Index) ? Color.Green : Color.Red;
        }
        else
        {
            foreColor = e.ForeColor;
        }

        // Copy the original event args, just tweaking the fore color.
        var tweakedEventArgs = new DrawItemEventArgs(
            e.Graphics,
            e.Font,
            e.Bounds,
            e.Index,
            e.State,
            foreColor,
            e.BackColor);

        // Call the original OnDrawItem, but supply the tweaked color.
        base.OnDrawItem(tweakedEventArgs);
    }
}

关于c# - 如何动态更改/设置 checkedListBox 项目前颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17588322/

相关文章:

c# - 将焦点放在按键上

c# - C#函数转VB,char值溢出报错

c# - Application.Run() 和 Form.ShowDialog() 有什么区别?

c# - CheckedListBox - 按文本搜索项目

c# - 在 for 循环中更改列表

c# - Linq 按匹配数排序

c# - [C#][XNA 3.1] 如何在一个 Windows 窗体中托管两个不同的 XNA 窗口?

winforms - 为什么我的 WindowsForm 在执行循环时没有响应

c# - 使用c#在一个单行数据库中插入多个checkedlistbox值