简体   繁体   English

以编程方式添加资源字典中的删除项

[英]programmatically add remove items from resource dictionary

I'm just new in wpf and am planning to use a listbox to generate recently opened or closed items. 我只是wpf的新手,我打算使用列表框来生成最近打开或关闭的项目。 Everytime a file is opened, it gets added permanently added into a resource dictionary of type listbox item. 每次打开文件时,都会将其永久添加到列表框项类型的资源字典中。

On the other hand, besides the listbox item is a button to remove the link. 另一方面,除了列表框项目之外,还有一个用于删除链接的按钮。

Is this possible? 这可能吗?

ResourceDictionary is a IDictionary . ResourceDictionary是一个IDictionary You can use the indexer to add/override items. 您可以使用索引器添加/覆盖项目。

myResourceDictionary["somekey"] = someObject;

And you can use the Add() and Remove() method. 您可以使用Add()Remove()方法。

As for your scenario I would prefer to use an ObservableCollection instead and bind your listbox to it. 至于你的场景,我宁愿使用ObservableCollection而是你的列表框绑定到它。

This is indeed possible and, in addition to bitbonk's answer, I would say this: 这确实是可能的,除了bitbonk的回答,我会这样说:

You probably don't want to have an ObservableCollection filled with ListBoxItems . 您可能希望ObservableCollection填充ListBoxItems ListBoxItem is a class that WPF uses for rendering and you'd not typically create these yourself. ListBoxItem是WPF用于渲染的类,您通常不会自己创建这些类。 If you make your data source a collection of (for example) FileInfo objects, you can use data templates to make the display of those items in the list appear however you wish. 如果您将数据源设置为(例如) FileInfo对象的集合,则可以使用数据模板使列表中的这些项目显示在您希望的位置。 This also has the benefit that you don't have to write code transform your data objects into a separate class just for display purposes. 这样做的好处是,您无需编写代码将数据对象转换为单独的类,仅用于显示目的。

(You'd likely use your own data/model type rather than FileInfo , but I don't know enough about your solution to suggest one.) (您可能使用自己的数据/模型类型而不是FileInfo ,但我对您的解决方案建议不够充分。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM