c# - 在 WPF C# 应用程序中执行标准形状实例的深层复制
问题描述
我有两个 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" ;
}
}
}
}
解决方案
如果您不需要保留任何依赖属性的值源,那么深度复制 wpf UI 非常简单。XamlWriter.Save(objcet)
并将XamlReader.Parse(string)
为您做到这一点。
var btn1 = new Button() { Content = "click me" };
var btn2 = (Button)XamlReader.Parse(XamlWriter.Save(btn1));
推荐阅读
- python - 根据字段名称和值从 JSON 中选择字段
- angular - 对象中的属性错误 | 角度 7
- html - CSS中的下拉文本框设计
- python - Python - 我可以从 excel 文件中取消透视表并将数据源转换为 pandas 数据框吗?
- python - 问号“?” 在 SQL 中替换 CREATE TABLE、DROP TABLE - 限制
- java - 无法创建与数据库服务器 MySQL 8.0 的连接
- c++ - C++03 根据成员函数值查找元素
- haskell - Haskell,在构建时堆栈“ExitFailure1”
- nginx - Nginx:在不更改 URL 的情况下重写文件
- java - 需要在字段中输入值,检查结果,然后在 Selenium Java 中添加一个字符