Reputation: 11
For example I have this simple markup in my MainWindow.xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Margin="10" Width="300" />
<Button Grid.Column="1" Margin="10" Width="300" />
</Grid>
When I start the application and resize the main window I can make it smaller then the buttons' sizes as it crops the buttons.
I have tried setting the MinWidth properties - that didn't work. The only way is to set the MinWidth of the whole window but it's not very maintainable solution.
UPDATE
Evetually I have found a solution.
I added event handler for MainWindow SizeChanged. with following code:
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
FrameworkElement topmost = (Content as FrameworkElement);
topmost.Measure(new Size(ActualWidth, ActualHeight));
MinHeight = topmost.DesiredSize.Height + 40;
MinWidth = topmost.DesiredSize.Width;
}
I found out that the Measure method of any FrameWorkelement forces it to calculate space it wants to occupy with the given amount of space it CAN occupy and considering all its child elements and stores it to the DesiredSize property. So I call the Measure method of the window's topmost element with the current size of the window and in the DesiredSize I get the minimum size of everything in the window. Then I set the MinHeight and the MinWidth of the window to this minimum size values. And it does the trick!
Upvotes: 1
Views: 1529
Reputation: 11151
While @Dimitry M's solution works, there's a simpler solution without magic values. Set SizeToContent="WidthAndHeight"
and bind an event listener to Window's ContentRendered
event:
<Window ...
SizeToContent="WidthAndHeight"
ContentRendered="MainWindow_OnContentRendered">
This will force the window to fit its contents, Then once it's rendered, we prevent resizing down by setting its minimum size to actual size.
private void MainWindow_OnContentRendered(object sender, EventArgs e)
{
MinWidth = ActualWidth;
MinHeight = ActualHeight;
}
Upvotes: 2
Reputation: 44068
Remove the Buttons' Height
.
<Button Grid.Column="0" Margin="10" />
<Button Grid.Column="1" Margin="10" />
this will cause the buttons to resize according to the Window Size.
Upvotes: 0