2013-07-11 6 views
4

아래 코드가 있습니다. 항목이 선택되어 있는지 여부에 따라 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 
      } 
     } 
} 

답변

4

난 당신이 같은 자신의 CheckedListBox item을 그릴 수 있다고 생각 : 당신이 다른 CheckedColor을 설정하려면

public class CustomCheckedListBox : CheckedListBox 
{ 
    public CustomCheckedListBox() 
    { 
     DoubleBuffered = true; 
    } 
    protected override void OnDrawItem(DrawItemEventArgs e) 
    {    
     Size checkSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, System.Windows.Forms.VisualStyles.CheckBoxState.MixedNormal); 
     int dx = (e.Bounds.Height - checkSize.Width)/2; 
     e.DrawBackground(); 
     bool isChecked = GetItemChecked(e.Index);//For some reason e.State doesn't work so we have to do this instead. 
     CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(dx, e.Bounds.Top + dx), isChecked ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal : System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal); 
     using (StringFormat sf = new StringFormat { LineAlignment = StringAlignment.Center }) 
     { 
      using (Brush brush = new SolidBrush(isChecked ? CheckedItemColor : ForeColor)) 
      { 
       e.Graphics.DrawString(Items[e.Index].ToString(), Font, brush, new Rectangle(e.Bounds.Height, e.Bounds.Top, e.Bounds.Width - e.Bounds.Height, e.Bounds.Height), sf); 
      } 
     }    
    } 
    Color checkedItemColor = Color.Green; 
    public Color CheckedItemColor 
    { 
     get { return checkedItemColor; } 
     set 
     { 
      checkedItemColor = value; 
      Invalidate(); 
     } 
    } 
} 

각 항목에 대해 각 항목 (예 : 컬렉션)에 CheckedColor 설정을 저장하고 Index을 사용하여 CheckedColor을 참조해야합니다. 그러나 나는 그것이 할 약간의 일이라고 생각합니다. 그래서 만약 당신이 그런 요구를 가지고 있다면, ListView 대신에 좋을 것입니다.

+0

줄 "bool isChecked = GetItemChecked (e.Index);" 그 항목을 디자이너로 드래그 앤 드롭하면 나를 위해 오류가 발생합니다. 이 문제를 해결하려면 Entreis를 추가해야합니다. 그러면 오류가 더 이상 발생하지 않습니다 (인덱스는 -1입니다. 그렇지 않으면 생각합니다). –

+0

귀하의 답변에 대해 감사드립니다. 그 점에 대해서는 확실하지 않습니다. 내가 이해하는 것처럼'e.Index'는 이벤트 처리기에서 유효해야합니다 (항목이 드로잉이 처리되기 전에 존재하기 때문에). 이 코드는 물론 잘 테스트되지 않았습니다. 또한 디자이너의 목록 항목을 끌어다 놓을 수있는 방법에 대해 확신 할 수 없습니다 (표준 Windows 폼 디자이너에서는 불가능하다는 것을 기억하는 한). 귀하의 의견은 다른 사람들이 코드를 개선하는 데 여전히 중요합니다. 마지막으로 나는 수년간 winforms를 프로그래밍하지 않았지만 지금은 그것에 관심이 없다. 감사. –

+0

와우 그게 빠른 반응 이었어 ^^ 3 년 만에 25 분의 반응 시간^-^어쨌든, 나는 당신에게 편집을 제안했다. 그리고 이것처럼 보이는 ControllBox를 만드는 법을 알고 있는가? 링크] (http://cosketch.com/Saved/pVwWicGW) –

2

나는 체크리스트 대신 ListView을 시도해야한다고 생각합니다. 필요한 속성이 있으며 원하는대로 사용자 지정할 수 있습니다. 그냥 trueCheckboxes 속성을 설정하고 코드에서 그런 데 ForeColor 추가

listView1.Items[i].ForeColor = Color.Red; 
1

자신을 그리는 것이 다소 복잡하기 때문에 실제로 원래 컨트롤을 그릴 수 있습니다. 단지 색상을 조정하면됩니다. 이것은 나의 제안입니다 :

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); 
    } 
} 
관련 문제