Никита Потапов
d5384363ab
Добавил возможность указать максимальное количество чекнутых Item; При достижении макс. количества последний чекнутый становится не чекнутым;
70 lines
2.1 KiB
C#
70 lines
2.1 KiB
C#
namespace Components
|
|
{
|
|
public partial class UserControlCheckedList : UserControl
|
|
{
|
|
private List<int> _lastCheckedIndexes = new List<int>();
|
|
public int MaxCheckedItemsCount { get; set; } = 1;
|
|
private EventHandler _onCheckedItemChangedEvent;
|
|
public event EventHandler CheckedItemChanged
|
|
{
|
|
add
|
|
{
|
|
_onCheckedItemChangedEvent += value;
|
|
}
|
|
remove
|
|
{
|
|
_onCheckedItemChangedEvent -= value;
|
|
}
|
|
}
|
|
public string CheckedItem
|
|
{
|
|
get
|
|
{
|
|
return checkedListBox.CheckedItems[0] as string ?? string.Empty;
|
|
}
|
|
set
|
|
{
|
|
if (checkedListBox.Items.Contains(value))
|
|
{
|
|
checkedListBox.SetItemCheckState(checkedListBox.Items.IndexOf(value), CheckState.Checked);
|
|
}
|
|
}
|
|
}
|
|
public UserControlCheckedList()
|
|
{
|
|
InitializeComponent();
|
|
}
|
|
public void SetCheckedListBoxValues(List<string> values)
|
|
{
|
|
ClearCheckedListBoxValues();
|
|
foreach (var item in values)
|
|
{
|
|
checkedListBox.Items.Add(item);
|
|
}
|
|
}
|
|
public void ClearCheckedListBoxValues()
|
|
{
|
|
checkedListBox.Items.Clear();
|
|
_lastCheckedIndexes.Clear();
|
|
}
|
|
private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
|
|
{
|
|
if (e.NewValue == CheckState.Checked)
|
|
{
|
|
_lastCheckedIndexes.Add(e.Index);
|
|
|
|
while (_lastCheckedIndexes.Count > MaxCheckedItemsCount)
|
|
{
|
|
checkedListBox.SetItemCheckState(_lastCheckedIndexes[0], CheckState.Unchecked);
|
|
}
|
|
}
|
|
else if (e.NewValue == CheckState.Unchecked)
|
|
{
|
|
_lastCheckedIndexes.Remove(e.Index);
|
|
}
|
|
|
|
_onCheckedItemChangedEvent?.Invoke(sender, e);
|
|
}
|
|
}
|
|
}
|