การสร้าง User Control ใช้เองใน C#

ทำไมต้องสร้าง User Control ใช้เอง

เพื่อให้ได้ Control ตัวใหม่ ที่เหมาะจะใช้เป็น Template เพือให้ง่ายต่อการแก้ไข และใส่ Effect ได้ง่ายขึ้น

วิธีการ

  1. คลิกขวา Add > New Item
  2. เลือก User Control ตั้งชื่อ File
  3. ปรับแต่หน้าตา User Control ตามต้องการ

แล้วถ้าต้องการใส่ Properties เพื่อให้แก้ไขค่าได้ล่ะ?

ให้ใส่ Code นี้เข้าไปใน .cs โดยสมมุติว่า Properties ที่จะเพิ่มชื่อว่า Text และเมื่อแก้ไขจะให้ไปแก้ค่า Text ของ txtBlock

        public string Text
        {
            get { return txtBlock.Text; }
            set { txtBlock.Text = value; }
        }

        // Using a DependencyProperty enables animation, styling, binding, etc.
        // อย่าลืมแก้ตรงนี้
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register(

                //ตรงนี้ใส่ชื่อ Properties
                "Text",                  // The name of the DependencyProperty
                //ใส่ชนิด Properties
                typeof(string),             // The type of the DependencyProperty

                //ชื่อ Class ของ Control
                typeof(MyMenuItem),       // The type of the owner of the DependencyProperty
                new PropertyMetadata(     // OnBlinkChanged will be called when Blink changes
                    false
                )
            );

จบครับ

การนำไปประยุกต์ใช้

สามารถใส่ Effect เป็น state ใน Control ได้ และยังใส่ Event ได้อีกด้วยประหยัดการ Code และแก้ไขได้ง่ายขึ้นอีกด้วย