วันเสาร์ที่ 26 กันยายน พ.ศ. 2558

เราจะเขียนโปรแกรมด้วย Xamarin Forms ให้กระชับและเร็วขึ้นได้อย่างไร (ตอนที่ 1 Grid)

   เวลาที่เราเขียนโปรแกรมด้วย Xamarin.Forms บางครั้งเราต้องเขียน Syntax ที่ยาวบ้าง แต่ถ้าเราเขียนหลาย ๆ ครั้ง อาจจะเสียเวลามาก ตัวอย่างเช่น เราจะสร้างตาราง 2 บรรทัด 2 คอลัมภ์ ด้วย Grid

Grid mainGrid = new Grid
{
    VerticalOptions = LayoutOptions.Fill,
    HorizontalOptions = LayoutOption.Fill,
    RowSpacing  =  0,
    ColumnSpacing = 0,
}

mainGrid.RowDefinitions.Add(

  new RowDefinition { Height = new GridLength(1,GridUnitType.Star)}
);
mainGrid.RowDefinitions.Add(
         new RowDefinition { Height = new GridLength(1,GridUnitType.Star)}
);

mainGrid.ColumnDefinitions.Add(

 new ColumnDefinition { Width = new GridLength(1,GridUnitType.Star)});
mainGrid.ColumnDefinitions.Add(

 new ColumnDefinition { Width = new GridLength(1,GridUnitType.Star)});

mainGrid.Children.Add(new Image(),0,2,0,2);


เขียนไปหลาย ๆ รอบ ก็เหนื่อยเหมือนกัน

เราสามารถแก้ด้วย การสร้างคลาสใหม่ (NeatGrid) ที่สืบทอดมาจากคลาส Grid ที่ต้องการ แล้วกำหนดสิ่งที่ต้องการในคลาสนั้น เช่น

    public class NeatGrid : Grid 
    {
        public NeatGrid ()
        {
            this.ColumnSpacing = 0;
            this.RowSpacing = 0;
            this.HorizontalOptions = LayoutOptions.Fill;
            this.VerticalOptions = LayoutOptions.Fill;
            this.BackgroundColor = Color.Transparent;
        }

        public virtual void ColumnStar(double star)
        {
            this.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (star, GridUnitType.Star) });
        }
        public virtual void RowStar(double star, bool isExtended = false)
        {
            this.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (star, GridUnitType.Star) });
        }

        public void Add(View view,int column = 0,int row = 0,int columnSpan = 1,int rowSpan = 1)
        {
            this.Children.Add (view,column,column+columnSpan,row,row+rowSpan);
        }
    }
หลังจากนั้น เราก็ใช้คลาสนี้บ่อยเท่าที่ต้องการ เช่น

            NeatGrid mainGrid = new NeatGrid();

            mainGrid.RowStar(1);
            mainGrid.RowStar(1); // สร้าง 2 บรรทัด
            mainGrid.ColumnStar(1);
            mainGrid.ColumnStar(1);// สร้าง 2 Column

            mainGrid.Add (new Image (), 0, 0, 2, 2);
สั้นลงเยอะเลย

แล้วได้เพิ่มกลไกการ Add ให้เข้าใจง่ายขึ้น

โดยพารามิเตอร์ที่ 3,4 คือ columnspan คือ บอกจำนวนคอลัมภ์ที่ใช้
                     rowspan    คือ บอกจำนวนบรรทัด

ตอนหน้าจะเป็นคิวของคลาสอื่น ๆ ที่เราจะช่วยกันปรับปรุงให้กระชับนะครับ

ไม่มีความคิดเห็น:

แสดงความคิดเห็น