How to keep a nested grid square without using ViewBox?
This is similar to how-do-i-keep-aspect-ratio-on-scalable-scrollable-content-in-wpf, with the following differences:
- I'd like to avoid side-effects of the ViewBox - while the grid should resize when the container resizes, some of the grid content should keep their sizes (buttons for example)开发者_如何学Go.
- I don't need aspect ratios other than 1:1 (maybe some binding tricks can be used?)
- Code behind is Ok, though if possible I'd like to avoid creating yet another container
You just need to bind one of the parameters Width
or Height
to the other:
<Image x:Name="image" Height="{Binding Width, ElementName=image}"/>
You should bind Grid's Width and Height to one value:
<!--Dont forget to specify source where MaxSizeParam lies-->
<Grid Width="{Binding MaxSizeParam}" Height="{Binding MaxSizeParam}"/>
MaxSizeParam you can provide wherever you want an in what manner you want. For example if grid has Button then on SizeChanged event of Button you should recalculate MaxSizeParam:
void button_SizeChanged(object sender, SizeChangedEventArgs e)
{
MaxSizeParam = e.NewSize.Width > e.NewSize.Height ? e.NewSize.Width : e.NewSize.Height;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("MaxSizeParam"));
}
精彩评论