Witam. Jak w temacie. Prosiłbym o refaktoryzację tego kodu bo czuję, że przekombinowałem, bo logika do tego jest prosta. A jakoś nie mogę tego uprościć. Wszystkie takie kontrolki na formie muszą zmieniać swoją wartość podczas kliknęcia. Jeśli zmieni wartość, czyli jest aktywna lub nie to zmienia swój kolor. Muszę mieć też mieć możliwość zmiany aktywnośći bez kliknięcia, np. w innej metodzie.
public class ButtonControl : Button
{
private int _value;
public int Value
{
get { return _value; }
set { _value = value; OnValueChanged(); }
}
public bool IsActive { get; set; }
public event EventHandler ValueChanged;
public ButtonControl()
{
InitializeComponent();
SetEvents();
}
protected virtual void OnValueChanged()
{
if (ValueChanged != null) ValueChanged(this, EventArgs.Empty);
}
public void SetEvents()
{
EventHandler clickHandler = (object from, EventArgs args) =>
{
if (Form1.activeButton != null && Form1.activeButton != this) Form1.activeButton.Value = 0;
if (Value == 1)
Value = 0;
else
{
Value = 1;
Form1.activeButton = this;
}
};
Click += clickHandler;
EventHandler valueHandler = (object from, EventArgs args) => SetActive();
ValueChanged += valueHandler;
}
private void SetActive()
{
if (Value == 1)
{
BackColor = Color.SteelBlue;
IsActive = true;
}
else
{
BackColor = default(Color);
IsActive = false;
}
}