希望对您有所帮助!
要在代码中画线,你应该这样做:
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
要调整画布大小,请read this:
Canvas 是唯一没有固有布局的面板元素
特征。画布具有默认的高度和宽度属性
零,除非它是自动调整大小的元素的子元素
它的子元素。 Canvas 的子元素永远不会调整大小,它们
只是定位在他们指定的坐标。这提供了
在固有尺寸限制或
不需要或不需要对齐。对于您想要孩子的情况
要自动调整大小和对齐的内容,通常最好
使用 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?