WPF custom control size override
I'm creating a custom WPF control which derives from Grid. It's a Chess board and so I want it's width to be the same as it's height. How can I ac开发者_运维知识库complish this?
Edit:
I tried the following.
private void cbcBoard_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.NewSize.Width != e.NewSize.Height)
{
double m = Math.Min(e.NewSize.Width, e.NewSize.Height);
cbcBoard.Width = m;
cbcBoard.Height = m;
}
}
It didn't work. Any ideas?
Thanks.
New solution/workaround. The UserControl can stay as it is, we'll leave the scaling to the parent container.
We can't accomplish Min(Width, Height) with just the UserControl because if we set the Height for it, then the parent container won't scale it Verticaly and the same goes for Width. If we try to juggle them around then there are situations where we end in an endless Width/Height resizing loop.
What we need is another hidden control in the same space that fills it completely and can tell us what its Width and Height is everytime it changes. Then we can use the Math.Min(Width, Height) solution. Something like this. Notice how both controls are in Grid.Row="1" and Grid.Column="1".
<Rectangle Name="availableSpace"
SizeChanged="availableSpace_SizeChanged"
Fill="Transparent"
Grid.Row="1"
Grid.Column="1"/>
<myLib:UserControl1 x:Name="userControl11"
Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Left"
VerticalAlignment="Top"/>
And then in the availableSpace_SizeChanged EventHandler
private void availableSpace_SizeChanged(object sender, SizeChangedEventArgs e)
{
double minValue = Math.Min(availableSpace.ActualWidth, availableSpace.ActualHeight);
userControl1.Width = minValue;
userControl1.Height = minValue;
}
Now we have 1:1 ratio of the UserControl and it will scale both Vertically and Horizontally
I think the simplest solution is to set the size of your UserControl
to some constant value where Height == Width
, and then drop the whole thing in a Viewbox
which will handle the scaling (whilst maintaining aspect ratio) for you:
<Viewbox>
<myLib:UserControl1 x:Name="userControl11" />
</Viewbox>
This does mean that your control will be 'stretched' rather than being resized, which might make it inappropriate for you, but it is easy to implement!
精彩评论