Programing

프로그래밍 방식으로 그리드 행 및 열 위치를 설정하는 방법

lottogame 2020. 10. 12. 07:05
반응형

프로그래밍 방식으로 그리드 행 및 열 위치를 설정하는 방법


Stackpanel 안에 두 개의 그리드가 있습니다. 첫 번째 그리드의 이름은 GridX입니다. 처음에는 그리드 내부에 Textboxes (RowDefs / ColumnDefs)의 2D 배열이 있습니다. XAML의 TextBox 정의는 다음과 같습니다.

<TextBox x:Name="A1" Grid.Row="4" Grid.Column="5" TextAlignment="Center" />

GridX의 일부와 동일한 위치에 프로그래밍 방식 으로 TextBlock 을 추가하고 싶습니다.

효과는 이러 야

<TextBlock Grid.Row="4" Grid.Column="5"
HorizontalAlignment="Left" VerticalAlignment="Top" Text="10" FontSize="8"/>

이것을 추가하는 방법. 나는 이것을 시도했다 :

TextBlock tblock = new TextBlock();
GridX.SetColumn(tblock, cIndex);
GridX.SetRow(tblock, rIndex);

그러나 실패했습니다.

다시 시도했습니다.

int rIndex = Grid.GetRow(txtBox);
int cIndex = Grid.GetColumn(txtBox);                               

TextBlock tblock = new TextBlock();
tblock.VerticalAlignment = VerticalAlignment.Top;
tblock.HorizontalAlignment = HorizontalAlignment.Left;
tblock.FontSize = 8;
tblock.Text = rc[i, j - 1];

Grid.SetColumn(tblock, cIndex);
Grid.SetRow(tblock, rIndex);

txtBox.MaxLength = 1;    

이제 문제는 TextBlock이 보이지 않는다는 것입니다. TextBox가 숨 깁니다. 도와 주셔서 감사합니다.


연결된 속성의 경우 값을 할당하려는 개체에서 SetValue를 호출 할 수 있습니다.

tblock.SetValue(Grid.RowProperty, 4);

또는 소유자 유형 (이 경우 SetRow)의 속성에 대해 정적 Set 메서드 (시도한 것과 같은 인스턴스 메서드가 아님)를 호출합니다.

Grid.SetRow(tblock, 4);

다음은 누군가를 도울 수있는 예입니다.

Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());

Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";

Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);

Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);

Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);

Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);

Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);

Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);

for (int i = 0; i < 6; i++)
{
    test.ColumnDefinitions.Add(new ColumnDefinition());

    Label t1 = new Label();
    t1.Content = "Test" + i;

    Grid.SetColumn(t1, i);
    Grid.SetRow(t1, 0);
    test.Children.Add(t1);
}

참고URL : https://stackoverflow.com/questions/3745594/how-to-set-grid-row-and-column-positions-programmatically

반응형