かきスタンプ

福岡でフリーランスの物流系のエンジニアやってます。

WPF:Grid上の好きなポジションに、動的に要素を配置

System.Windows.Controls.Grid は、Grid.Row と Grid.Column にて、要素のポジションを指定します。
 
動的に要素を配置する場合、SetValue にて、Grid.RowProperty と Grid.ColumnProperty を設定するとOKです。

実行例

f:id:kakisoft:20180410001143p:plain

ソース

xaml

<Window x:Class="PracticeWPF.MyWindow19"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PracticeWPF"
        mc:Ignorable="d"
        Title="MyWindow19" Height="200" Width="200">
    <Grid>
        <Grid x:Name="myGrid01" Width="150" Height="150">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>
        </Grid>
    </Grid>
</Window>

cs側

using System.Windows;
using System.Windows.Controls;

namespace PracticeWPF
{
    /// <summary>
    /// Gridの指定位置に要素を追加
    /// </summary>
    public partial class MyWindow19 : Window
    {
        public MyWindow19()
        {
            InitializeComponent();

            SetGridItems();
        }

        private void SetGridItems()
        {
            Button b0_0 = new Button();
            b0_0.Content = "0-0";
            b0_0.SetValue(Grid.RowProperty, 0);
            b0_0.SetValue(Grid.ColumnProperty, 0);
            myGrid01.Children.Add(b0_0);

            Button b0_2 = new Button();
            b0_2.Content = "0-2";
            b0_2.SetValue(Grid.RowProperty, 0);
            b0_2.SetValue(Grid.ColumnProperty, 2);
            myGrid01.Children.Add(b0_2);

            Button b1_1 = new Button();
            b1_1.Content = "1-1";
            b1_1.SetValue(Grid.RowProperty, 1);
            b1_1.SetValue(Grid.ColumnProperty, 1);
            myGrid01.Children.Add(b1_1);

            Button b2_2 = new Button();
            b2_2.Content = "2-2";
            b2_2.SetValue(Grid.RowProperty, 2);
            b2_2.SetValue(Grid.ColumnProperty, 2);
            myGrid01.Children.Add(b2_2);
        }
    }
}