Work around for CreateControlCore being called too early

I have a simple button control and editor
Sometimes I like to make the button show in a master detail view.
This was causing an issue with the CreateControlCore firing before the button had been initialized.
Here is my work around

    [PropertyEditor(typeof(MyButton), true)]
    public class MyButtonEditor : WinPropertyEditor 
    {
        public MyButtonEditor(Type objectType, IModelMemberViewItem model) : base(objectType, model)
        {
        }
        private bool initialized;
        public override bool IsCaptionVisible => false;

        protected override object CreateControlCore()
        {
            //var myButton = PropertyValue as MyButton;
            var control = new MyButtonControl();
            //if (myButton == null) return control;
            //control.SetButtonPressed(myButton.ButtonClicked);
            //control.simpleButton1.Text = myButton.Text;
            //control.simpleButton1.ToolTip = myButton.ToolTip;

            return control;
        }

        protected override void ReadValueCore()
        {
            InitializeMyButtonIfNeeded();
            base.ReadValueCore();
        }

        protected override void WriteValueCore()
        {
            base.WriteValueCore();
        }

        private void InitializeMyButtonIfNeeded()
        {
            if (initialized) return;
            if (PropertyValue is not MyButton myButton) return;
            var ctrl = Control as MyButtonControl;
          
            ctrl.SetButtonPressed(myButton.ButtonClicked);
            ctrl.simpleButton1.Text = myButton.Text;
            ctrl.simpleButton1.ToolTip = myButton.ToolTip;
            initialized = true;
        }
    }
    public class MyButton
    {
        public string Text { get; set; }
        public Action ButtonClicked { get; set; }
        public string ToolTip { get; set; }
    }
   public partial class MyButtonControl : XtraUserControl
    {
        public MyButtonControl()
        {
            InitializeComponent();
        }

        public event Action ButtonPressed = delegate { };

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            ButtonPressed();
        }

        public void SetButtonPressed(Action myButtonButtonClicked)
        {
            ButtonPressed = myButtonButtonClicked;
        }
    }
1 Like