Search code examples
wpfwpf-controlswpfdatagrid

How to use SetColumnSpan?


I am using the normal Grid, and adding Labels to from code, like tihs:

int a = 5;
Label lb = new Label();
lb.Content = a;

Grid.SetColumn(lb,i);
Grid.SetRow(lb, 1);
MyGrid.Children.Add(lb);
Grid.SetColumnSpan(lb,3);

The Label is added correctly to the Grid, but the columnspan is ineffective.Is it possible to do something like this?


Solution

  • Your code is ok. If you want to check this you should assign to the label content more data and grid property ShowGridLines (msdn) set to true.

    Example:

    <Grid x:Name="MyGrid" ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
    </Grid>
    

    code-behind:

    Label lb = new Label();
    lb.Content = "1234567890123456789012345678901234567890";
    
    Grid.SetColumn(lb, 1);
    Grid.SetRow(lb, 1);
    MyGrid.Children.Add(lb);
    Grid.SetColumnSpan(lb, 3);
    

    Result:

    enter image description here