How to delete a Tab Item based off of it's name or header

心不动则不痛 提交于 2020-01-05 04:14:21

问题


This question is similar to this question I asked earlier today. The difference is, now I would like to delete a Tab Item referenced by it's name or header. Can I call Remove in a fashion similar to the answer I got on this question?

This is what I've tried:

tabControl.Items.Remove = tabControl.Items //Changes tab according to TreeView
                        .OfType<TabItem>().SingleOrDefault(n => n.Name == stringValue);

Can I use something like this? If so, how?


回答1:


I don't know much about removing from wpf, however this code is way more likely to work than what you have posted. Remove is a method, you can't assign it a value, so you have to isolate the item you want to remove, check to make sure it isn't null, then pass the object into the Remove method.

var tabToDelete = tabControl.Items.OfType<TabItem>().SingleOrDefault(n => n.Name == stringValue);
if (tabToDelete != null) // Since you chose to use SingleOrDefault, we have to check to make sure it isn't null before we try to remove it.
tabControl.Items.Remove(tabToDelete);

However, I strongly suggest you take a look at WPF - Best way to remove an item from the ItemsSource since it goes into details about checking IF the item CAN be removed, and even if the Remove method is available to that control.



来源:https://stackoverflow.com/questions/18278781/how-to-delete-a-tab-item-based-off-of-its-name-or-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!