Search code examples
c#wpfgridstylesborder

Border style can apply only once time


Into the Grid, I try to apply around all my TextBlock a Border with Style. I have no problem with XAML code but visually, when I apply my second Border with the same Style around my TextBlock in the grid (Col: 0 Row: 1) this one moves in the grid (Col: 0 Row: 0).

In my Window.Resources:

        <Style x:Key="BorderTextBlockStyle" TargetType="{x:Type Border}">
           <Setter Property="BorderThickness" Value="1"/>
           <Setter Property="BorderBrush" Value="Black"/>
           <Setter Property="CornerRadius" Value="5"/>
           <Setter Property="Grid.Column" Value="{Binding}"/>
           <Setter Property="Grid.Row" Value="{Binding}"/>
        </Style>

In my Window:

<Grid VerticalAlignment="Top">            
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>
            <Border Style="{StaticResource BorderTextBlockStyle}">
                <TextBlock Grid.Column="0" Grid.Row="0" Text="Firstname" Style="{StaticResource GridTitleStyle}"/>
            </Border>
            <Border Style="{StaticResource BorderTextBlockStyle}">
                <TextBlock Grid.Column="1" Grid.Row="0" Text="Lastname" Style="{StaticResource GridTitleStyle}"/>
            </Border>
        </Grid>

Visual OK: This picture shows the first border with style work
Visual FAIL: this picture shows the second border with style fail

Why ?
How i can simply define in my xaml Border Style an multiple use ?


Solution

  • You should set Grid.Row and Grid.Column for Border not TextBlock

         <Border Grid.Column="0" Grid.Row="0" Style="{StaticResource BorderTextBlockStyle}">
                <TextBlock Text="Firstname" Style="{StaticResource GridTitleStyle}"/>
         </Border>
         <Border Grid.Column="1" Grid.Row="0" Style="{StaticResource BorderTextBlockStyle}">
                <TextBlock Text="Lastname" Style="{StaticResource GridTitleStyle}"/>
         </Border>
    

    and remove these lines in Resource

        <Setter Property="Grid.Column" Value="{Binding}"/>
        <Setter Property="Grid.Row" Value="{Binding}"/>