Mixer
Mixer

Reputation: 1332

Dynamically change the size of the control?

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.

Upvotes: 0

Views: 3196

Answers (1)

Sebastian Edelmeier
Sebastian Edelmeier

Reputation: 4167

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...

Upvotes: 3

Related Questions