Search code examples
c#debuggingpropertiesnesteddesigner

Nested properties wont "Stay" set


I am trying to make a custom library of controls. I at first thought I had the form finished and totally working but I didn't. Instead of asking on how to fix my problem with the form, I will ask it with my button.

I'm making a custom button that is extensively customizable with each state it's in being able to set each color different as well as the text.

I also have implemented a way to make the button have different orientation which is currently the easiest way to solve my problem because I'm sure once this is solved I can solve the rest of my problems.

I will first show you some code then explain.

namespace OurCSharp.OurControls.Core.Buttons.Button
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Linq;
    using System.Windows.Forms;

    using OurCSharp.OurControls.Core.Buttons.Button.Properties;
    using OurCSharp.OurControls.Core.Buttons.Enums;
    using OurCSharp.OurControls.Core.Buttons.Interfaces;

    [DefaultEvent("Click")]
    public class OurButton : Control////, IOurButtonRoot
    {
        private Color _borderColor = Color.FromArgb(255, 25, 25, 25);
        private Color _textColor = Color.FromArgb(255, 150, 150, 150);

        // TODO We will see if this is actually ignored or not; it may be though because it is its default value.
        private SizeF _textSizeF = SizeF.Empty;

        private IOurButtonDesigner _buttonDesigner;



        /// <summary>
        /// The designers for each state of the button.
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public OurButtonDesigner ButtonDesign { get; set; }

        /// <summary>
        /// Gets or sets the background color for the control.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Drawing.Color"/> that represents the background color of the control. The default is the value of the <see cref="P:System.Windows.Forms.Control.DefaultBackColor"/> property.
        /// </returns>
        /// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
        [DefaultValue(typeof (Color), "255, 75, 75, 75")]
        public override Color BackColor
        {
            get { return base.BackColor; }
            set
            {
                base.BackColor = value;
                this.Invalidate();
            }
        }

        /// <summary>
        /// Gets or sets the foreground color of the control.
        /// </summary>
        /// <returns>
        /// The foreground <see cref="T:System.Drawing.Color"/> of the control. The default is the value of the <see cref="P:System.Windows.Forms.Control.DefaultForeColor"/> property.
        /// </returns>
        /// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
        [DefaultValue(typeof(Color), "255, 150, 150, 150")]
        public override Color ForeColor
        {
            get { return base.ForeColor; }
            set
            {
                base.ForeColor = value;
                this.Invalidate();
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker.
        /// </summary>
        /// <returns>
        /// true if the surface of the control should be drawn using double buffering; otherwise, false.
        /// </returns>
        [DefaultValue(true)]
        protected override bool DoubleBuffered { get { return base.DoubleBuffered; } set { } }

        public OurButton()
        {
            // TODO Might have to add in property for this with a description
            // TODO Gotta update the minimum size...
            base.AutoSize = true;

            base.DoubleBuffered = true;

            this.Padding = new Padding(6, 2, 6, 2);

            base.Text = @"OurButton";

            this.ButtonDesign = new OurButtonDesigner(this);

            Debug.WriteLine(this.ButtonDesign.Clicked.Text);



            Debug.WriteLine(3);
            this.Margin = new Padding(3);

            // TODO Need to re-calcualte size aswell with padding is changed.
            // TODO Also need to re-calculate on when the font is changed.




            base.TextChanged += (sender, args) => this.Invalidate();





            base.Text = @"OurButton";

            // TODO May not need this hear, might just be able to call it in the 'OnCreateControl'
            this.Invalidate();
        }

        public void UpdateSize() { this.Size = this.CalculateSize(); }

        private SizeF MeassureString(string str) => this.CreateGraphics().MeasureString(str, this.Font);

        /// <summary>
        /// Raises the <see cref="M:System.Windows.Forms.Control.CreateControl"/> method.
        /// </summary>
        protected override void OnCreateControl()
        {
            Debug.WriteLine(1);
            base.OnCreateControl();
            Debug.WriteLine(2);

            this._buttonDesigner = this.Enabled ? this.ButtonDesign.Normal : this.ButtonDesign.Disabled;

            base.BackColor = this._buttonDesigner.BackColor;
            base.ForeColor = this._buttonDesigner.TextColor;

            var stringToArea = new KeyValuePair<string, float>(string.Empty, 0F);

            foreach (var str in new[]
                                {
                                    this.ButtonDesign.Normal.Text,
                                    this.ButtonDesign.Hovered.Text,
                                    this.ButtonDesign.Clicked.Text,
                                    this.ButtonDesign.Disabled.Text
                                })
            {
                var area = 0F;

                Debug.WriteLine(str);



                // TODO This may not work.
                if (stringToArea.Value >= (area = this.CalculateStringArea(str))) { continue; }

                stringToArea = new KeyValuePair<string, float>(str, area);
            }

            this._textSizeF = this.MeassureString(stringToArea.Key);

            this.Size = this.CalculateSize();
            this.Text = this._buttonDesigner.Text;

            Debug.WriteLine("HERE");

            Debug.WriteLine("{0}, {1}, {2}", this.Text, stringToArea.Key, stringToArea.Value);

            this.Invalidate();
        }

        // Calculating the Area is beter than Parimeter because Parimeter could be used for something like a Polygon.
        private float CalculateStringArea(string str)
        {
            var sizeF = this.MeassureString(str);
            return sizeF.Width * sizeF.Height;
        }

        ////private Size CalculateSize()
        ////    =>
        ////        (this._textSizeF =
        ////         new SizeF(this.ButtonDesign.Orientation == ButtonOrientation.Verticle
        ////                       ? new Size((int)this._textSizeF.Height + this.Padding.Bottom + this.Padding.Top,
        ////                                  (int)this._textSizeF.Width + this.Padding.Left + this.Padding.Right)
        ////                       : new Size((int)this._textSizeF.Width + this.Padding.Left + this.Padding.Right,
        ////                                  (int)this._textSizeF.Height + this.Padding.Bottom + this.Padding.Top))).ToSize
        ////            ();

        private Size CalculateSize()
        =>
            (
             new SizeF(this.ButtonDesign.Orientation == ButtonOrientation.Verticle
                           ? new Size((int)this._textSizeF.Height + this.Padding.Bottom + this.Padding.Top,
                                      (int)this._textSizeF.Width + this.Padding.Left + this.Padding.Right)
                           : new Size((int)this._textSizeF.Width + this.Padding.Left + this.Padding.Right,
                                      (int)this._textSizeF.Height + this.Padding.Bottom + this.Padding.Top))).ToSize
                ();

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.MouseClick"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.Windows.Forms.MouseEventArgs"/> that contains the event data. </param>
        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            // TODO Using a trenary may use more resources as it's always going to update the UI even if it's already disabled..
            /*
             * Need re-assign text before the 'BackColor' and 'ForeColor' because once those are called,
             * the button is going to set invalidated.
             */
            this.Text =
                (this._buttonDesigner = this.Enabled ? this.ButtonDesign.Clicked : this.ButtonDesign.Disabled).Text;
            this.BackColor = this._buttonDesigner.BackColor;
            this.ForeColor = this._buttonDesigner.TextColor;

            // TODO May have to set the state back to something different after being clicked
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.MouseEnter"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data. </param>
        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);

            // TODO Using a trenary may use more resources as it's always going to update the UI even if it's already disabled..
            /*
             * Need re-assign text before the 'BackColor' and 'ForeColor' because once those are called,
             * the button is going to set invalidated.
             */
            this.Text =
                (this._buttonDesigner = this.Enabled ? this.ButtonDesign.Hovered : this.ButtonDesign.Disabled).Text;
            this.BackColor = this._buttonDesigner.BackColor;
            this.ForeColor = this._buttonDesigner.TextColor;
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.MouseLeave"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data. </param>
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);

            // TODO Using a trenary may use more resources as it's always going to update the UI even if it's already disabled..
            /*
             * Need re-assign text before the 'BackColor' and 'ForeColor' because once those are called,
             * the button is going to set invalidated.
             */
            this.Text =
                (this._buttonDesigner = this.Enabled ? this.ButtonDesign.Normal : this.ButtonDesign.Disabled).Text;
            this.BackColor = this._buttonDesigner.BackColor;
            this.ForeColor = this._buttonDesigner.TextColor;
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.Paint"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data. </param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            var g = e.Graphics;
            var p = new Pen(this._borderColor);

            var clientRect = this.ClientRectangle;

            clientRect.Width--;
            clientRect.Height--;

            if (this._buttonDesigner.PaintBorder)
            {
                p.Color = this._buttonDesigner.BorderColor;
                g.DrawRectangle(p, clientRect);
            }

            var b = new SolidBrush(this.ForeColor);

            switch (this.ButtonDesign.Orientation)
            {
                case ButtonOrientation.Horizontal:
                    g.DrawString(this.Text,
                                 this.Font,
                                 b,
                                 (int)this._textSizeF.Width / 2F + this.Padding.Left,
                                 this.Padding.Top,
                                 new StringFormat()
                                 {
                                     Alignment = StringAlignment.Center
                                 });
                    break;
                case ButtonOrientation.Verticle:
                    g.DrawString(this.Text,
                                 this.Font,
                                 b,
                                 this.Padding.Top,
                                 (int)this._textSizeF.Width / 2F + this.Padding.Left,
                                 new StringFormat()
                                 {

                                     FormatFlags = StringFormatFlags.DirectionVertical,
                                     LineAlignment = StringAlignment.Center
                                 });
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            ////g.DrawString(this.Text,
            ////             this.Font,
            ////             b,
            ////             3,
            ////             this.Padding.Top, ////this._textSizeF.Height / 2F + 3F,
            ////             this.ButtonDesign.Orientation == ButtonOrientation.Verticle
            ////                 ? new StringFormat
            ////                   {
            ////                       Alignment = StringAlignment.Center,
            ////                       FormatFlags = StringFormatFlags.DirectionVertical
            ////                   }
            ////                 : new StringFormat
            ////                   {
            ////                       Alignment = StringAlignment.Center
            ////                   });
        }
    }
}

Here ButtonBaseClass

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OurCSharp.OurControls.Core.Buttons.Button.Properties
{
    using System.ComponentModel;

    using OurCSharp.OurControls.Core.Buttons.Button.Properties.SubProperties;
    using OurCSharp.OurControls.Core.Buttons.Enums;
    using OurCSharp.OurControls.Core.Buttons.Interfaces;

    public class OurButtonDesigner : IOurButtonBase
    {
        private readonly OurButton _ourButton;

        private ButtonOrientation _orientation = ButtonOrientation.Horizontal;

        public OurButtonDesigner(OurButton ourButton)
        {
            this._ourButton = ourButton;
            this.Normal = new OurButtonHovered(ourButton);
            this.Hovered = new OurButtonHovered(ourButton);
            this.Clicked = new OurButtonClicked(ourButton);
            this.Disabled = new OurButtonDisabled(ourButton);
        }

        /// <summary>
        /// The orientation of the button.
        /// </summary>
        [DefaultValueAttribute(typeof(ButtonOrientation), "Horizontal")]
        public ButtonOrientation Orientation
        {
            get { return this._orientation; }
            set
            {
                this._orientation = value;
                this._ourButton.UpdateSize();
                this._ourButton.Invalidate();
            }
        }

        /// <summary>
        /// Designer for the button when in the 'Normal' state.
        /// </summary>
        public IOurButtonDesigner Normal { get; }

        /// <summary>
        /// Designer for the button when in the 'Hovered' state.
        /// </summary>
        public IOurButtonDesigner Hovered { get; }

        /// <summary>
        /// Designer for the button when in the 'Clicked' state.
        /// </summary>
        public IOurButtonDesigner Clicked { get; }

        /// <summary>
        /// Designer for the button when in the 'Designer' state.
        /// </summary>
        public IOurButtonDesigner Disabled { get; }
    }
}

I severely apologize for how trashy it looks, I usually don't have my code like this. It is usually really neat.

Back on topic.

Lets just focus on the Orientation.

I also know there is a lot of crud in my code that should not be there, but it's just what I have tried and failed.

The orientation property is shown in the property gird at design time and if I change it, it will update the button on the form to either go verticle or horizontal. The default is horizontal.

Now when I change it to vertical, it changes like said before, but once I run the code to test it, it goes back to the default horizontal.

I'm thinking the problem is I have instantiating each class when the code runs, but I cannot figure out a way to fix it.

I really need help, can someone please help me?


Solution

  • You need to tell the designer to set the properties of the nested object:

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public OurButtonDesigner ButtonDesign { get; set; }