10

CircleWPF窗户上画画。问题是我无法添加TextCircle. 代码如下:

public Graphics()
{
    InitializeComponent();

    StackPanel myStackPanel = new StackPanel();
    Ellipse myel = new Ellipse();
    SolidColorBrush mscb = new SolidColorBrush();
    mscb.Color = Color.FromArgb(255, 255, 0, 0);
    myel.Fill = mscb;
    myel.StrokeThickness = 2;
    myel.Stroke = Brushes.Black;
    myel.Width = 100;
    myel.Height = 100;
    //string str = "hello";
    myStackPanel.Children.Add(myel);
    this.Content = myStackPanel;
}

请在这方面帮助我。

4

2 回答 2

22

形状只是形状,如果您想添加文本,则将形状和TextBlock带有文本的 a 添加到一个公共容器中,该容器将它们放在彼此的顶部,例如Grid没有行或列的 a。

在 XAML 中:

<Grid>
    <Ellipse Width="100" .../>
    <TextBlock Text="Lorem Ipsum"/>
</Grid>

C#

var grid = new Grid();
grid.Children.Add(new Ellipse { Width = 100, ... });
grid.Children.Add(new TextBlock { Text = "Lorem Ipsum" });
于 2013-05-05T16:40:53.810 回答
4

或者,如果您更喜欢直接控制绘图位置,则可以在 Canvas 中使用直接定位:

我的示例定义了一个 UI 控件,该控件在其中绘制带有文本的矩形:

XAML

<UserControl x:Class="DrawOnCanvas"
         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" 
         xmlns:local="clr-namespace:MySample"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">
<Grid>
    <Canvas x:Name="DrawCanvas" Height="30"/>
</Grid>

后面的代码:

    // You might e.g. call this in the constructor of DrawOnCanvas
    internal void DrawRectWithText()
    {
        var rect = new System.Windows.Shapes.Rectangle();
        rect.Stroke = new SolidColorBrush(Colors.Black);
        rect.Fill = new SolidColorBrush(Colors.Beige);

        rect.Width = 100;
        rect.Height = 100;

        // Use Canvas's static methods to position the rectangle
        Canvas.SetLeft(rect, 100);
        Canvas.SetTop(rect, 100);

        var text = new TextBlock()
        {
            Text = task.Title,
        };

        // Use Canvas's static methods to position the text
        Canvas.SetLeft(text, 90);
        Canvas.SetTop(text, 90);

        // Draw the rectange and the text to my Canvas control.
        // DrawCanvas is the name of my Canvas control in the XAML code
        DrawCanvas.Children.Add(rect);
        DrawCanvas.Children.Add(text);
    }
于 2019-09-09T20:20:01.080 回答