Alexus Alexus - 8 months ago 46
C# Question

UserControl resizing at runtime

Hi fellow programmers,

I'm working on a WPF software that uses a Canvas to display and move graphic objects.
These graphic objects are UserControls containing labels or rectangles :

<UserControl x:Class="DashEditor.Views.MovableObject"
mc:Ignorable="d" >

<Grid Name="ControlLayout">

<StackPanel x:Name="DisplayPanel" >

<Canvas x:Name="graphicObjectCanvas" Width="100" Height="50">

<Viewbox x:Name="graphicObjectViewBox" Width="100" Height="50" IsEnabled="False" Canvas.Left="0" Canvas.Top="0" Stretch="Fill"/>




I need to resize these UserControls, I saw examples with thumbs but I can't figure out how to use it in a UserControl.

Thank you for your help !

Answer Source

OK, I found a working solution to resize my canvas graphic objects. I added a thumb into my usercontrol which become visible when a graphic object is selected :

<Grid Name="ControlLayout">

    <StackPanel x:Name="DisplayPanel">
        <Border x:Name="CanvasBorder" BorderThickness="1">
            <Canvas x:Name="graphicObjectCanvas" Width="100" Height="50" Background="Aquamarine">
                <Viewbox x:Name="graphicObjectViewBox" Width="100"  Height="50" IsEnabled="False" Stretch="Fill"/>

                <Thumb x:Name="myThumb" Canvas.Left="80" Canvas.Top="30" Width="20" Height="20" DragDelta="myThumb_DragDelta" Visibility="Hidden"
                       PreviewMouseLeftButtonDown="myThumb_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="myThumb_PreviewMouseLeftButtonUp" BorderBrush="Blue" BorderThickness="2"/>




And this is the code behind that changes my graphic object's properties :

    private void myThumb_DragDelta(object sender, DragDeltaEventArgs e)
        double yadjust = graphicObjectViewBox.Height + e.VerticalChange;
        double xadjust = graphicObjectViewBox.Width + e.HorizontalChange;
        if ((xadjust >= 0) && (yadjust >= 0))
            graphicObjectViewBox.Width = xadjust;
            graphicObjectViewBox.Height = yadjust;
            graphicObjectCanvas.Width = xadjust;
            graphicObjectCanvas.Height = yadjust;
            Width = (int)xadjust;
            Height = (int)yadjust;
            XapParent.Width = (int)xadjust;
            XapParent.Height = (int)yadjust;
            Canvas.SetLeft(myThumb, Canvas.GetLeft(myThumb) + e.HorizontalChange);
            Canvas.SetTop(myThumb, Canvas.GetTop(myThumb) + e.VerticalChange);