Set usercontrol size According to the Controls inside it

1.8k Views Asked by At

hi i want Set usercontrol size According to the Controls inside it how i can do this? long time ago I used the propretis SizeToContent , but I can not find it right now

2

There are 2 best solutions below

0
RezaNoei On BEST ANSWER

@zahra_rajabi, Generally setting width and height properties to "Auto" will automatically sets width and height of a container according to its contents.

Set your main container (width, height) in Usercontrol to Auto to achieve SizeToContent.

* **Remember: DesignWidth and DesignHeight are usefull only on design time

0
Frenchy On

'Here, you could use layouttransform or rendertransform

sorry for my poor english..

for example:

<UserControl 
    x:Class="Setup.WPF.Gauges.SwitchOff_On_View"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:cal="http://www.caliburnproject.org"
    xmlns:ikriv="clr-namespace:Setup.WPF.Converters"
    mc:Ignorable="d" d:DesignHeight="150" d:DesignWidth="70"
    x:Name="usercontrol" Height="150" Width="70" RenderTransformOrigin="0.5,0.5"
    VerticalAlignment = "Top" HorizontalAlignment = "Left" Focusable="False" ClipToBounds="True" ToolTip="{Binding ToolTip}"
    cal:Message.Attach="[Event MouseEnter] = [Action MouseEnter($eventArgs)]">

    <UserControl.LayoutTransform>
        <TransformGroup>
            <RotateTransform x:Name="rotation" Angle="{Binding angle}"/>
            <ScaleTransform x:Name="scale" ScaleX="{Binding scaleX}" ScaleY="{Binding ElementName=scale, Path=ScaleX}"/>
        </TransformGroup>
    </UserControl.LayoutTransform>

    <Grid>  
        :
        :
        :
    </Grid>
</UserControl>

the value RenderTransformOrigin="0.5,0.5 is important because you notify where is your center.

First You have to calculate the Scale Factor,

for example if you desire Size (width) = 100 pixels (width at startup), you calulate the ScaleX from a width size of element known, width value of image or usercontrol

ScaleX = Size / sizeelement

you bind the Scale in ScaleTranform (rotatetransform is not needed )

you could do that in C# (code behind) so .

regards