Reputation: 472
I wish to add a sidebar to a window that works the same as in Windows File Explorer and other programs. I want the width of the sidebar to be absolute but resizeable and the main panel to take up the remaining space. The problem is the splitter doesn't stop after reaching the main panel's minimum width and in fact will continue past the right edge of the window.
XAML sample:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="170"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*" MinWidth="50"/>
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Width="3" HorizontalAlignment="Stretch"/>
</Grid>
I have found this question repeated often but the only answer that works is to make both columns have proportional width which doesn't help here. There was a possible solution posted here by the question asker but they never showed how to implement it.
I subclassed GridSplitter, and added logic to keep the splitter within the bounds of the Grid. The new splitter sets the columns/rows it is moving to proportional before moving, then restores them to their original GridUnitType state when dragging is complete (so the rows resize properly when the window resizes).
Upvotes: 0
Views: 1380
Reputation: 493
In your example it is possible to set the MaxWidth property for the first column. So I added a SizeChanged event to the grid and set the MaxWidth in the code behind.
XAML:
<Grid SizeChanged="Grid_SizeChanged" >
<Grid.ColumnDefinitions>
<ColumnDefinition Name="FirstColumn" Width="170"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Width="3" HorizontalAlignment="Stretch" />
</Grid>
Code behind:
private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
FirstColumn.MaxWidth = Application.Current.MainWindow.ActualWidth - 50;
}
I know this is an ugly solution, but this problem also made me really angry. So if you don't want to spend a lot of time for such a trivial thing, i would recommend you use this quick and dirty approach.
Upvotes: 2