Bind to the width of a GridSplitter Column WPF

Struggled with this one this afternoon, it seems a simple request, bind the width of a Grid Column to a value so it can be saved on program close and shared between Pages in a Navigation control.

The problem is that the width of a ColumnDefinition is not a simple value, it can be Auto, Star or Pixel value, Hence the binding kind of only works one way, I’m sure you could write a value converter to solve this as well but my simple solution is as follows.

XAML

<Grid DockPanel.Dock="Top">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="{Binding Path=DetailWidth, Mode=OneWay}/>
    </Grid.ColumnDefinitions>
    <Grid x:Name="ScheduleGrid" />
    <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch" Width="5" DragCompleted="GridSplitter_DragCompleted"/>
    <Grid Grid.Column="1" />
</Grid>

Code behind

private void GridSplitter_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
    DetailWidth = (int)((sender as GridSplitter).Parent as Grid).ColumnDefinitions[1].Width.Value;
}

The binding in the ColumnDefinition handles the get and we manually do the set in the event handler.

Leave a Reply

Your email address will not be published.