UserControl在运行时调整大小

时间:2016-11-25 15:16:52

标签: c# wpf user-controls

嗨其他程序员,

我正在开发一个使用Canvas显示和移动图形对象的WPF软件。 这些图形对象是包含标签或矩形的UserControl:

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

我需要调整这些UserControl的大小,我看到拇指的例子,但我无法弄清楚如何在UserControl中使用它。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

好的,我找到了一个工作解决方案来调整画布图形对象的大小。 我在我的usercontrol中添加了一个拇指,当选择了图形对象时,它会变得可见:

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

这是改变我的图形对象属性的代码:

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