Thursday, January 26, 2012

DataBinding to a WPF grid's cell

The idea was to use the data binding capabilities of WPF to ensure that a given element placed inside a grid's cell stays square (i.e. width = height). The problem is that it is not possible to directly access the height of a given row... Thus the trick is to place a border (zero thickness = not visible) inside that row and bind the element that should stay square to it.

For example like that:


<Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="100*"/>
            <RowDefinition Height="10*" />
            <RowDefinition Height="30*" />
        Grid.RowDefinitions>
        <Grid Grid.Row="0" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100*" />
                <ColumnDefinition Width="10*" />
            Grid.ColumnDefinitions>
            <Border Grid.Column="0" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" x:Name="MyBorder" />
            <WindowsFormsHost Grid.Column="0" Grid.Row="0" Width="{Binding ElementName=MyBorder, Path=ActualHeight}" Name="host" VerticalAlignment="Stretch" Loaded="host_Loaded"/>
            <my:ColorScaleViewer Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" x:Name="colorScaleViewer1"/>
        Grid>
Grid>

No comments:

Post a Comment