0

I created a class derived from UserControl
My task is to control the size proportions of height and width. (If the container is inserted to control will resize it.) I need the control to be strictly square.

What should be done to change the new dimensions of the control? SizeChangedEventArgs.NewSize property is read only.

private void MyControl_SizeChanged(object sender,SizeChangedEventArgs e)
{
    if (e.NewSize.Height!=e.NewSize.Width)
    {
        // to-do ?
    }
}

Width and Heigth in my case are NaN since the mode is set to Auto. I can not change manually Width or Height property since then Control will automatically fixed size and does not change when you scale grid in which it is placed.

Mixer
  • 1,292
  • 3
  • 22
  • 41

1 Answers1

3

If you want a control to be exactly square, the easiest way is to use a binding like so:

<Control Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"/>

Edit OK, seems like you can go well with your event handler:

FrameworkElement control =(sender as FrameworkElement);
double longerSideLength = (control.Width >= control.Height ? control.Width : control.Height);
control.Width = longerSideLength;
control.Height = longerSideLength;

You might want to add some validation to that to reduce call count...

Sebastian Edelmeier
  • 4,095
  • 3
  • 39
  • 60
  • the situation is a little more difficult, I want to kind of uniform. if (w> h) w = h; if (h> w) h = w; – Mixer Mar 01 '13 at 09:26
  • Would it helpt to put your control in a [viewbox](http://wpftutorial.net/ViewBox.html)? – Sebastian Edelmeier Mar 01 '13 at 09:28
  • I used at the beginning ViewBox for this purpose but I had to stop using it cause is described here: http://stackoverflow.com/questions/14957794/viewbox-stretch-blurs-the-controls – Mixer Mar 01 '13 at 09:30