view ServerMonitor/Controls/CheckControl.cs @ 4:3142e52cbe69

Lots more progress
author Brad Greco <brad@bgreco.net>
date Sun, 10 Feb 2019 20:51:26 -0500
parents 453ecc1ed9ea
children 7127d5b5ac75
line wrap: on
line source

´╗┐using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ServerMonitorApp
{
    /// <summary>Base class for check controls</summary>
    /// <remarks>This control should never be used directly, but marking it abstract causes problems with the designer.</remarks>
    public partial class CheckControl : UserControl
    {
        public Type CheckType => GetCheckType(GetType());

        public CheckControl()
        {
            InitializeComponent();
        }

        private void CheckControl_Load(object sender, EventArgs e)
        {
            CheckGroupBox.Text = Helpers.GetDisplayName(CheckType);

            IEnumerable<Panel> panels = CheckGroupBox.Controls.OfType<Panel>();
            foreach (Panel panel in panels)
            {
                CheckBox mainCheckBox = panel.Controls.OfType<CheckBox>().OrderBy(c => c.Left).FirstOrDefault();
                if (mainCheckBox != null)
                {
                    mainCheckBox.CheckedChanged += CheckControl_CheckedChanged;
                    DisablePanelByCheckBox(mainCheckBox);
                }
            }
        }

        private void CheckControl_CheckedChanged(object sender, EventArgs e)
        {
            DisablePanelByCheckBox((CheckBox)sender);
        }

        private void DisablePanelByCheckBox(CheckBox checkBox)
        {
            foreach (Control control in checkBox.Parent.Controls)
            {
                if (control != checkBox)
                    control.Enabled = checkBox.Checked;
            }
        }

        public virtual void LoadCheck(Check check) { }

        public virtual void UpdateCheck(Check check) { }

        public static CheckControl Create(Type CheckType)
        {
            Type checkControlType = typeof(CheckControl).Assembly.GetTypes().FirstOrDefault(t => GetCheckType(t) == CheckType);
            return checkControlType == null ? null : (CheckControl)Activator.CreateInstance(checkControlType);
        }

        private static Type GetCheckType(Type type)
        {
            return type.GetAttribute<CheckTypeAttribute>()?.CheckType;
        }
    }
}