Markus2k
Markus2k

Reputation: 165

Bind width on UI element to Width of another UI Element

I wanted to bind Width of a column header to the Width of the header defined. However the code doesn't work. If I specify the Width explicitly (Width="100"), it works fine. Can someone shed some light and tell me what is wrong with the code below?

<dataGrid:DataGridTemplateColumn x:Name="pdpCol" Width="100">
        <dataGrid:DataGridTemplateColumn.Header>
            <Grid HorizontalAlignment="Stretch">
                <TextBlock Text="PDP" VerticalAlignment="Center" HorizontalAlignment="Center" 
                    TextWrapping="Wrap" Width="{Binding ElementName=pdpCol,Path=ActualWidth }" TextAlignment="Center" />
            </Grid>
        </dataGrid:DataGridTemplateColumn.Header>
</dataGrid:DataGridTemplateColumn>

Upvotes: 4

Views: 11671

Answers (3)

Samuel DR
Samuel DR

Reputation: 1231

Check if ActualWidth is being set, I think it will work if you just use Path=Width.

Upvotes: 0

Oliver Hanappi
Oliver Hanappi

Reputation: 12336

Remove the HorizontalAlignment="Center" from the TextBlock or set the property to Stretch. Then the TextBlock will consume all available width automatically. Furthermore, if you don't show anything else than the textblock, then remove the grid and use just the TextBlock. You also need to set HeaderTemplate rather the Header directly.

<dataGrid:DataGridTemplateColumn x:Name="pdpCol" Width="100" Header="PDP">
    <dataGrid:DataGridTemplateColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" TextAlign="Center" />
        </DataTemplate>
    </dataGrid:DataGridTemplateColumn.HeaderTemplate>
</dataGrid:DataGridTemplateColumn>

Best Regards,
Oliver Hanappi

Upvotes: 6

wpfwannabe
wpfwannabe

Reputation: 14867

Try the markup below. Please note the use of HeaderStyle to stretch the template and HeaderTemplate to actually define the visual template for your Header="PDP" item.

<dataGrid:DataGridTemplateColumn x:Name="pdpCol" Width="100" Header="PDP">
    <dataGrid:DataGridTemplateColumn.HeaderStyle>
         <Style TargetType="{x:Type Primitives:DataGridColumnHeader}">
              <Setter Property="HorizontalContentAlignment" Value="Stretch" />
              <Setter Property="VerticalContentAlignment" Value="Center" />
         </Style>
    </dataGrid:DataGridTemplateColumn.HeaderStyle>
    <dataGrid:DataGridTemplateColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" TextAlignment="Center" />
        </DataTemplate>
    </dataGrid:DataGridTemplateColumn.HeaderTemplate>
</dataGrid:DataGridTemplateColumn>

Upvotes: 1

Related Questions