Search code examples
wpflistviewbindingdatatemplate

Binding the control's property in its DataTemplate


I have a custom control where I have modified a ListView. I have a DataTemplate which shows each item as an icon of width 128 and a label beneath it.

<DataTemplate x:Key="AeroIconTemplate">
    <Grid VerticalAlignment="Top" Margin="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Image Grid.Row="0" Source="{Binding Image}" Width="128"
               MaxHeight="128" Margin="0"/>
        <TextBlock Grid.Row="1" Text="{Binding Title}" Foreground="Black"
                   TextWrapping="WrapWithOverflow" Margin="0" 
                   TextTrimming="CharacterEllipsis" Width="128" MaxHeight="60" />
    </Grid>
</DataTemplate>

Now I have added a property to the ListView itself called IconSize. This takes an integer between 16 and 256.

I want to bind the Width, MaxHeight of the Image and the Width of the TextBlock to this property. So whenever the IconSize property is changed the template is adjusted in size. As you can see I am currently binding some stuff to the data object (the image source and the label text), but in this case I want to bind to the ListView control.

How do I do this?

Thanks!


Solution

  • You can use the RelativeSource for that:

    ... Width="{Binding IconSize,RelativeSource={RelativeSource AncestorType=ListView}}" ...
    

    Be sure to define the correct type, since the WPF ListView does not have the property IconSize. You may need to define your class.