Sergey Aldoukhov
Sergey Aldoukhov

Reputation: 22744

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:

  1. 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).
  2. I don't need aspect ratios other than 1:1 (maybe some binding tricks can be used?)
  3. Code behind is Ok, though if possible I'd like to avoid creating yet another container

Upvotes: 0

Views: 1763

Answers (2)

Danail Nachev
Danail Nachev

Reputation: 19851

You just need to bind one of the parameters Width or Height to the other:

<Image x:Name="image" Height="{Binding Width, ElementName=image}"/>

Upvotes: 1

Eugene Cheverda
Eugene Cheverda

Reputation: 8940

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"));
        }

Upvotes: 1

Related Questions