WPF Grid 用 C# 代碼后台設置


WPF GridC# 代碼后台設置

運行環境:Window7 64bit,.NetFramework4.61,C# 6.0; 編者:烏龍哈里 2017-02-21


參考:

章節:

  • 動態增加行列及控件放置
  • 設置Grid的行列尺寸

正文:

一、動態增加行列及控件放置

要用到
Grid.SetRow(控件名, 行序號)
Grid.SetColumn(控件名, 列序號),
另一種寫法是:
控件實例.SetValue(Grid.RowProperty, 行序號)
控件實例.SetValue(Grid.ColumnProperty, 列序號)

示例1演示如何增減行和放置控件:

示例1:

public partial class MainWindow : Window
{
    private int rowCount = 0;
    private int colCount = 0;
    private int itemCount = 0;

    public MainWindow()
    {
        InitializeComponent();
        grdShow.ColumnDefinitions.Add(new ColumnDefinition());
        grdShow.ColumnDefinitions.Add(new ColumnDefinition());
        grdShow.ColumnDefinitions.Add(new ColumnDefinition());
        grdShow.RowDefinitions.Add(new RowDefinition());
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        itemCount++;
        TextBlock tbk = new TextBlock() { Text = $"Item {itemCount.ToString()}" };
        if (colCount % 3 == 0)
        {
            grdShow.RowDefinitions.Add(new RowDefinition());
            colCount = 0;
            rowCount++;
        }
        tbk.SetValue(Grid.RowProperty, rowCount);
        tbk.SetValue(Grid.ColumnProperty, colCount++);
        
        //Grid.SetRow(tbk, rowCount);
        //Grid.SetColumn(tbk, colCount++);

        grdShow.Children.Add(tbk);
    }

    private void btnDelete_Click(object sender, RoutedEventArgs e)
    {
        itemCount = grdShow.Children.Count;
        if (itemCount > 0)
        {
            grdShow.Children.RemoveRange((itemCount-1) / 3 *3,(itemCount-1) %3 +1);
            grdShow.RowDefinitions.RemoveAt((itemCount-1) / 3);
        }
    }
}

結果如下圖:

二、設置Grid的行列尺寸

設置 Grid 行列的尺寸要用到 GridLength 結構。以下示例是設置3行,第1行是固定高度24,第2行是動態高度 1*,第3行也是動態高度 2*,我這里所謂的動態高度是指隨着窗口尺寸的變化而變化的尺寸。

示例3:

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

Button btn1 = new Button {Content="Fix",Margin=new Thickness(2)};
Grid.SetRow(btn1, 0);
Button btn2 = new Button {Content="1*", Margin = new Thickness(2) };
Grid.SetRow(btn2, 1);
Button btn3 = new Button {Content="2*", Margin = new Thickness(2) };
Grid.SetRow(btn3, 2);

grdShow.Children.Add(btn1);
grdShow.Children.Add(btn2);
grdShow.Children.Add(btn3);

運行結果如下圖,第2行的 Button 是第3行的 Button 高度的1/2,而且隨着窗口變化而變化。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: