代码之家  ›  专栏  ›  技术社区  ›  serhio

自动调整WPF控件的大小

  •  0
  • serhio  · 技术社区  · 14 年前

    * North Star

    <UserControl x:Class="StopPoint.UserControl1"
             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" 
             d:DesignHeight="300" d:DesignWidth="300">
        <Canvas>
            <Path Fill="SkyBlue" Stroke="Black" StrokeThickness="2">
                <Path.Data>
                    <EllipseGeometry Center="10, 10" RadiusX="4" RadiusY="4"/>
                </Path.Data>
            </Path>
            <TextBlock Text="North Star" Canvas.Left="20" Canvas.Top="20"/>
        </Canvas>
    </UserControl>
    

    我会在小组里有很多明星。我可以自动调整控件的大小,使其尽可能小吗?

    洛杉矶: <Window SizeToContent="WidthAndHeight">...</Window>

    3 回复  |  直到 14 年前
        1
  •  1
  •   Holstebroe    14 年前

    不如把它包在一个简单的堆叠面板里?

    <UserControl x:Class="StopPoint.UserControl1"
             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" 
             d:DesignHeight="300" d:DesignWidth="300">
    
        <StackPanel Orientation="Horizontal">
            <Ellipse Margin="4" Stroke="Black" Fill="Yellow" Height="10" Width="10"/>
            <TextBlock Text="North Star">
                <TextBlock.RenderTransform>
                    <RotateTransform Angle="45"/>
                </TextBlock.RenderTransform>
             </TextBlock>
        </StackPanel>
    </UserControl>
    
        2
  •  1
  •   Alex Paven    14 年前

    您描述的自动调整大小行为是许多容器控件的默认行为。尽量不要像霍尔斯特布罗建议的那样使用画布。也可以尝试观察变换-你可以应用旋转和平移变换来实现你描述的效果。

        3
  •  0
  •   Gishu    14 年前

    WPF方法是让父元素询问子元素他们需要多少空间(测量阶段),然后根据可用空间告诉他们实际得到了多少空间(排列阶段)。

    在这里,您希望父对象的大小由子对象所需的空间决定。所以呢

            <!-- 36 <= 20  (canvas.top) + 16 (textblock.actualheight) -->
            <!--75 <= 20 (canvas.left) + 55 (textblock.actualwidth)-->
            <Canvas Background="SkyBlue" Height="36" Width="75">
            <TextBlock Canvas.Left="25" Text="{Binding ElementName=label, Path=ActualHeight}"/>
            <Path x:Name="dot" Fill="SkyBlue" Stroke="Black" StrokeThickness="2">
                    <Path.Data>
                        <EllipseGeometry Center="10, 10" RadiusX="4" RadiusY="4"/>
                    </Path.Data>
                </Path>
    
            <TextBlock x:Name="label" Text="North Star" Canvas.Left="20" Canvas.Top="20"/>