如何克隆包含所有子项的 WPF 网格?
我的 WPF 窗口中有几个控件。我将窗口分为 4 个部分。如果我单击左上角的部分,我想在另一个弹出窗口中复制该部分的内容。 我想要复制的是一个可以包含很多不同控件的网格,例如:切换按钮、按钮、面板...源自 ItemsControl、Control...以及 DependencyProperty、ObservableCollection 等。
我尝试过:
- XamlWriter.Save(数据);
- XamlServices.Save(数据);
但我总是有这些错误:
- 无法序列化泛型类型“System.Collections.ObjectModel.ObservableCollection`1 或
- 解析签名时抛出了 BadImageFormatException。这可能是由于缺乏通用上下文。确保 提供 genericTypeArguments 和 genericMethodArguments 并 包含足够的上下文。
I have several controls in my WPF window. I have divided the window into 4 sections. If I click on the section in the upper left, I want to copy the contents of this section in another window popup.
What I want to copy is a grid that can contain a lot of different controls, ex: togglebutton, button, panel... derived from ItemsControl, Control... and with DependencyProperty, ObservableCollection etc..
I tried :
- XamlWriter.Save(data);
- XamlServices.Save(data);
but I always have these errors :
- Cannot serialize a generic type 'System.Collections.ObjectModel.ObservableCollection`1 or
- A BadImageFormatException has been thrown while parsing the signature. This is likely due to lack of a generic context. Ensure
genericTypeArguments and genericMethodArguments are provided and
contain enough context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应该克隆 XAML 本身,这是残酷且错误的方式。
看看下面可能的 MVVM 解决方案。假设单个 DataGird 代表单个业务项目,因此您需要以下内容:
ObservableCollection- Items { get; set; }
)ICommand CopyItem
,并且在命令处理程序中实际上仅复制 Item 业务实体的实例并将其添加到Items
列表中,WPF 通过绑定反映此更改,UI 将由新的 ListViewItem 更新,DataGrid 表示刚刚复制的 Item 的详细信息有用的链接:
You should not clone XAML itself, this is brutal and wrong way.
Take a look at the possible MVVM solution below. Let's say single DataGird represents a single business Item, so you need following:
ObservableCollection<Item> Items { get; set; }
)ICommand CopyItem
and in command handler actually copyiing only instance of the Item business entity and adding it to theItems
list, WPF reflects this changes via bindings and UI will be updated by a new ListViewItem with a DataGrid representing a details of just copied ItemUseful links: