WPF画布填充

时间:2018-08-15 14:34:16

标签: c# wpf canvas

我目前有一个WPF窗口,其Canvas是600 x400。是否可以缩放或自动放大,以使线条尽可能多地占据600x600?

   <Border>
          <Canvas x:Name="cMap" Width="600" Height="400">
                 <Line X1="5" Y1="5" X2 ="10" Y2="10" StrokeThickness="2" Stroke="Black"/>
                 <Line X1="10" Y1="10" X2 ="15" Y2="25" StrokeThickness="2" Stroke="Black"/>
          </Canvas>
   </Border>

我的意图是通过代码而非XAML以编程方式添加行。

谢谢。

2 个答案:

答案 0 :(得分:2)

不确定确切的用例是什么,但是使用ViewBox可能会受益:

<Border>
    <Viewbox Stretch="Uniform">
        <Canvas x:Name="cMap" Width="15" Height="25">
            <Canvas.LayoutTransform>
                <ScaleTransform />
            </Canvas.LayoutTransform>
            <Line X1="5" Y1="5" X2 ="10" Y2="10" StrokeThickness="2" Stroke="Black"/>
            <Line X1="10" Y1="10" X2 ="15" Y2="25" StrokeThickness="2" Stroke="Black"/>
        </Canvas>
    </Viewbox>
</Border>

答案 1 :(得分:1)

希望这对您有帮助!

要在代码中绘制线条,应执行以下操作:

Line line = new Line();
    Thickness thickness = new Thickness(101,-11,362,250);
    line.Margin = thickness;
    line.Visibility = System.Windows.Visibility.Visible;
    line.StrokeThickness = 4;
    line.Stroke = System.Windows.Media.Brushes.Black;
    line.X1 = 10;
    line.X2 = 40;
    line.Y1 = 70;
    line.Y2 = 70;

不要忘记添加:

myCanvas.Children.Add(line); 

将这些行放在某个位置

来自:Drawing lines in code using C# and WPF

要调整画布大小,请阅读以下内容:

(MSDN)画布是唯一没有固有布局特征的面板元素。画布的默认“高度”和“宽度”属性为零,除非它是自动调整其子元素大小的元素的子元素。画布的子元素永远不会调整大小,它们只是位于其指定的坐标处。这为不需要或不需要固有大小限制或对齐的情况提供了灵活性。对于您希望子内容自动调整大小和对齐方式的情况,通常最好使用Grid元素。

因此,作为解决方案,您可以将其置于GRID内或使用以下代码:

public class CanvasAutoSize : Canvas
{
protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
{
    base.MeasureOverride(constraint);
    double width = base
        .InternalChildren
        .OfType<UIElement>()
        .Max(i => i.DesiredSize.Width + (double)i.GetValue(Canvas.LeftProperty));

    double height = base
        .InternalChildren
        .OfType<UIElement>()
        .Max(i => i.DesiredSize.Height + (double)i.GetValue(Canvas.TopProperty));

    return new Size(width, height);
}
}

在您的XAML:

 <local:CanvasAutoSize VerticalAlignment="Top" HorizontalAlignment="Left"></local:CanvasAutoSize>

来自:WPF: How to make canvas auto-resize?