Alexus Alexus - 3 days ago 6
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
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"/>

</Canvas>

</StackPanel>

</Grid>




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

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"/>

            </Canvas>
        </Border>

    </StackPanel>

</Grid>

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);
        }
    }
Comments