C# 如何在 WPF 画布上绘制矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14782158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:59:10  来源:igfitidea点击:

How to draw a rectangle on a WPF canvas

c#wpfcanvas

提问by Sheena

I'm trying to draw a Rectangleon a Canvasas follows:

我想画Rectangle上一个Canvas如下:

System.Windows.Shapes.Rectangle rect;
rect = new System.Windows.Shapes.Rectangle();
rect.Stroke = new SolidColorBrush(Colors.Black);
rect.Fill = new SolidColorBrush(Colors.Black);
rect.Width=200;
rect.Height=200;
Canvas.SetLeft(rect,0);
Canvas.SetTop(rect,0);
front_canvas.Children.Add(rect);

Why would this code not draw a rectangle?

为什么这段代码不绘制矩形?

The canvas is defined in the associated XAML as follows:

画布在关联的 XAML 中定义如下:

<Canvas Height="200" Width="200" Name="front_canvas" Grid.Row="1" Grid.Column="0">      
</Canvas>

The canvas shows up fine. I can tell because of the gap it leaves in the layout grid.

画布显示良好。我可以分辨出它在布局网格中留下的间隙。

采纳答案by Reed Copsey

This should draw your rectangle as a 200x200 black square, provided front_canvasis displayed correctly.

如果front_canvas显示正确,这应该将您的矩形绘制为 200x200 的黑色正方形。

Why would this code not draw a rectangle?

为什么这段代码不绘制矩形?

The main reasons this would not draw are:

这不会绘制的主要原因是:

  • front_canvasis not visible
  • front_canvasis not in the visual tree and being displayed correctly
  • Some other FrameworkElementis obscuring front_canvas, at least the upper left corner.
  • There is another object in the canvas at a higher z order.
  • front_canvas不可见
  • front_canvas不在可视化树中并正确显示
  • 其他一些FrameworkElement是模糊的front_canvas,至少是左上角。
  • 画布中还有一个更高 z 阶的对象。

Note that you'd typically also want to set StrokeThicknessif you want to see the Strokeyou specify.

请注意,StrokeThickness如果您想查看Stroke您指定的内容,您通常还需要设置。

回答by SHEKHAR SHETE

To View Rectangle you must specify the StrokeThicknessand set any Integervalue greater than zero:

要查看矩形,您必须指定StrokeThickness并设置任何Integer大于零的值:

rect.StrokeThickness=2;