我有一个 WPF 应用程序,它允许用户在treeview
. 这些子项是从一个单独的窗口中创建的,并添加到主窗口中。我还想实现一个删除方法,该方法将从单独的窗口中删除主窗口子项。
这些是我的想法以及一些代码:
//Okay button -- Delete sub-items in main window TreeView
private void button2_Click(object sender, RoutedEventArgs e)
{
//Query for Window1
var mainWindow = Application.Current.Windows
.Cast<Window1>()
.FirstOrDefault(window => window is Window1) as Window1;
//Name of header that needs to be located
string header = textBox1.Text;
//While treeview from main window contains subitems
while (!mainWindow.treeView.Items.IsEmpty)
{
//Find TreeView subitem with matching header
//? - not sure on code
//Delete TreeView subitem
//I'm guessing it has something to do with
//mainWindow.treeView.Items.Remove(At?)....
}
}
我的评论表明我不确定。我已经正确查询了我的主窗口,并为我想要查找的标题设置了一个字符串值。我已经设置了一个循环来搜索我的treeview
,但不知道完成工作的确切代码。请告诉我我应该使用的代码。
根据答案修改代码
我正在尽我所能理解你的回答。我已经在评论中解释了我想要做的事情。我认为我在正确的轨道上,但是当我尝试使用RemoveAll
. 我需要包括某种 ausing resourceDictionary
吗?
代码修订
非常感谢你一直陪着我。编译器仍在为调用RemoveAll
.
//Okay button -- Delete location and corrusponding block
private void button2_Click(object sender, RoutedEventArgs e)
{
//Close Delete Window
this.Close();
//Query for Window1
var mainWindow = Application.Current.Windows
.Cast<Window1>()
.FirstOrDefault(window => window is Window1) as Window1;
//Name of header that needs to be located
string header = textBox1.Text;
//Treeview under operation from main window
TreeViewItem items = mainWindow.treeViewItem;
//Delete corresponding node
RemoveAll(items, p => string.Equals(p.Header, header));
}
//REMOVE ALL METHOD - for use with button_click ^
public void RemoveAll(ItemCollection items, Predicate<TreeViewItem> isValid)
{
for (int i = items.Count - 1; i >= 0; i--)
{
TreeViewItem vItem = (TreeViewItem)items[i];
if (isValid(vItem))
{
items.RemoveAt(i);
}
else
{
RemoveAll(vItem.Items, isValid);
}
}
}
生成错误
错误 1:“...(项目)...”的最佳重载方法匹配有一些无效参数。
错误 2:参数“1”:无法转换System.Windows.Controls.TreeViewitem
为“System.Windows.Controls.ItemCollection”。
谢谢你。