c# WPF.如何将椭圆动态添加到画布中

本文关键字:添加 动态 布中 WPF | 更新日期: 2023-09-27 18:05:37

我试图添加一些椭圆随机位置到我的画布,但我可以看到他们在我的画布上。程序编译得很安全。代码:

for (int i = 0; i < FirefliesCount; ++i)
            {
                Firefly CurrentFirefly = new Firefly();
                CurrentFirefly.Speed = Randomer.Next(1, 3);
                CurrentFirefly.Body = new Ellipse();
                CurrentFirefly.Body.Margin = new Thickness(Randomer.Next(10, (int)MainCanvas.Width - 10),
                                                           Randomer.Next(10, (int)MainCanvas.Height - 10),
                                                           0, 0);
                CurrentFirefly.Body.Fill = Brushes.Black;
                CurrentFirefly.Body.Height = MainCanvas.Height / 4;
                CurrentFirefly.Body.Width = 1.5 * CurrentFirefly.Body.Height;
                MainCanvas.Children.Add(CurrentFirefly.Body);
            }

And firefly class:

class Firefly
{
    public Ellipse Body { get; set; }
    public int Speed { get; set; }
}

c# WPF.如何将椭圆动态添加到画布中

可能您没有设置MainCanvasWidthHeight属性;那么它们的值是NaN,因此你不会看到椭圆。我的建议是使用ActualWidthActualHeight代替,并延迟添加省略号,直到画布加载。下面是一个例子:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        MainCanvas.Loaded += MainCanvas_Loaded;
    }
    void MainCanvas_Loaded(object sender, RoutedEventArgs e)
    {
        Init();
    }
    private void Init()
    {
        const int FirefliesCount = 100;
        Random Randomer = new Random();
        for (int i = 0; i < FirefliesCount; ++i)
        {
            Firefly CurrentFirefly = new Firefly();
            CurrentFirefly.Speed = Randomer.Next(1, 3);
            CurrentFirefly.Body = new Ellipse();
            CurrentFirefly.Body.Margin = new Thickness(Randomer.Next(10, (int)MainCanvas.ActualWidth - 10),
                                                       Randomer.Next(10, (int)MainCanvas.ActualHeight - 10),
                                                       0, 0);
            CurrentFirefly.Body.Fill = Brushes.Black;
            CurrentFirefly.Body.Height = MainCanvas.ActualHeight / 4;
            CurrentFirefly.Body.Width = 1.5 * CurrentFirefly.Body.Height;
            MainCanvas.Children.Add(CurrentFirefly.Body);
        }
    }
}

对应的xaml文件如下所示:

<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Canvas x:Name="MainCanvas"/>
</Window>