我有两个Rectangle实例,我想将一个实例的属性复制到另一个实例,但是下面的代码导致对副本的更改会影响原始对象。
我相信我需要对原始矩形进行深层复制以避免这种行为,但是我该怎么做?
C#WPF应用程序。
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SpecialButton tmp = new SpecialButton();
tmp.Update();
}
public class SpecialButton
{
public Rectangle Original_Properties { get; set; }
public Rectangle Copy_Properties { get; set; }
public void Update()
{
Original_Properties = new Rectangle();
Copy_Properties = new Rectangle();
Original_Properties.StrokeThickness = 1;
Original_Properties.Stroke = Brushes.White;
Original_Properties.Width = 20;
Original_Properties.Height = 20;
Original_Properties.Tag = "exampleTag";
Copy_Properties = Original_Properties; // this needs to be a deep copy i think.
Copy_Properties.Width = Copy_Properties.Width / 2;
Copy_Properties.Height = Copy_Properties.Height / 2;
Copy_Properties.StrokeThickness = 2;
Copy_Properties.Tag = Original_Properties.Tag + "_selected" ;
}
}
}
}
答案 0 :(得分:0)
如果您不需要保留任何依赖项属性的值源,则深度复制wpf UI非常简单。 XamlWriter.Save(objcet)
和XamlReader.Parse(string)
将为您做到这一点。
var btn1 = new Button() { Content = "click me" };
var btn2 = (Button)XamlReader.Parse(XamlWriter.Save(btn1));