Question

I have the following XAML:


<GridView x:Key="myGridView">
    <GridViewColumn CellTemplate="{StaticResource myTemplate}" />
</GridView>

<DataTemplate x:Key="myTemplate">
    <ContentPresenter Content="{Binding}" />
</DateTemplate>

When I use it, I want the contentpresenter to have the same width as the GridViewColumn. So far, I've tried using the RelativeSource binding but I can't seem to get the GridViewColumn at all.

How do I get the ActualWidth from the parent GridViewColumn from the ContentPresenter in my DataTemplate?

Was it helpful?

Solution

The problem with GridView is that there is no notion of cells as visual elements in the generated control hierarchy. In order for your ContentPresenter to be wide as the column you should set the HorizontalContentAlignment property of the ListViewItem to Stretch. This way the ContentPresenter will stretch to the available width, which is the width of the column.

Here is a sample XAML which illustrates this:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Grid>
      <Grid.Resources>
         <DataTemplate x:Key="leftTemplate">
            <ContentPresenter HorizontalAlignment="Left" Content="{Binding}"/>
         </DataTemplate>
         <DataTemplate x:Key="rightTemplate">
            <ContentPresenter HorizontalAlignment="Right" Content="{Binding}"/>
         </DataTemplate>
         <GridView x:Key="myGridView">
            <GridViewColumn Width="150" CellTemplate="{StaticResource rightTemplate}" Header="Right"/>
            <GridViewColumn Width="150" CellTemplate="{StaticResource leftTemplate}" Header="Left"/>
         </GridView>
         <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
         </Style>
      </Grid.Resources>
      <ListView Margin="10" View="{StaticResource myGridView}">
         <ListViewItem Content="item 1"/>
         <ListViewItem Content="item 2"/>
         <ListViewItem Content="item 3"/>
         <ListViewItem Content="item 4"/>
         <ListViewItem Content="item 5"/>
      </ListView>
   </Grid>
</Page>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top