C# 以编程方式创建的UIElement';取消链接';当局部变量值设置为新的UIElement时

C# 以编程方式创建的UIElement';取消链接';当局部变量值设置为新的UIElement时,c#,wpf,C#,Wpf,希望标题不要含糊不清,我不知道该怎么说。我试图做的(作为一个基本示例)是以编程方式将一个矩形添加到画布,然后在稍后的某个点将局部变量更改为具有不同属性的新矩形,并在画布上进行更新 // First rectangle Rectangle rect = new Rectangle() { Width = 50, Height = 50, Fill = Brushes.Red, Margin = new Thickness(20, 20, 0, 0) }; // A

希望标题不要含糊不清,我不知道该怎么说。我试图做的(作为一个基本示例)是以编程方式将一个矩形添加到画布,然后在稍后的某个点将局部变量更改为具有不同属性的新矩形,并在画布上进行更新

// First rectangle
Rectangle rect = new Rectangle()
{
    Width = 50,
    Height = 50,
    Fill = Brushes.Red,
    Margin = new Thickness(20, 20, 0, 0)
};

// Add it to the canvas
mainCanvas.Children.Add(rect);

// Change something about the rectangle, which works
rect.Fill = Brushes.Black;

// Create new rectangle
Rectangle newRect = new Rectangle()
{
    Width = 15,
    Height = 20,
    Fill = Brushes.Blue,
    Margin = new Thickness(20, 20, 0, 0)
};

// Set the original rectangle to the new rectangle
rect = newRect;

// Canvas rectangle is no longer 'linked' to the rect variable :(

您正在重新分配
rect
变量,但这不会影响画布。画布只知道用于指向的旧矩形
rect
rect
只是对矩形的引用。将其添加到画布时,画布将复制引用。它不再继续使用
rect
变量。因此,将
rect
更改为引用新矩形不会改变画布,因为画布仍然引用原始矩形

您可能希望执行以下操作。我只是想尝试一下,所以您可能需要查找适当的方法,但希望这能给您提供指导

mainCanvas.Children.Remove(rect); //take the old rectangle off the canvas
rect = newRect;
mainCanvas.Children.Add(rect); //replace the new rectangle on the canvas

就这样!这非常简单,变量存储在另一个类中,并通过方法在该类中重新分配,因此无法访问画布。我只是将它作为参数传递给canvas,并使用了您建议的代码。干杯