我有一个TreeView
包含带有数字的子节点的项目的程序headers
。向其中添加子节点时,我TreeViewItem
想以数字方式添加它们,但我不知道如何在其他节点之间添加节点。
我猜我会调用一个函数,该函数将对子节点进行排序,将标头转换为integers
,将标头与输入的值进行比较,然后在节点标头大于输入的值时停止。必须在标头大于要添加的新节点的节点之前输入新节点。
这是最好的方法,还是有更好的方法?请演示解决此问题的最简单方法。仅供参考,我TreeViewItem
在我的主窗口中,并且正在从一个单独的窗口进行处理。
这应该让您了解我如何将子节点添加到我的TreeViewItem
:
//Global boolean
// bool isDuplicate;
//OKAY - Add TreeViewItems to location & Checks if location value is numerical
private void button2_Click(object sender, RoutedEventArgs e)
{
//Checks to see if TreeViewItem is a numerical value
string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
//If not numerical value, warn user
if (isNum == false)
MessageBox.Show("Value must be Numerical");
else //else, add location
{
//close window
this.Close();
//Query for Window1
var mainWindow = Application.Current.Windows
.Cast<Window1>()
.FirstOrDefault(window => window is Window1) as Window1;
//declare TreeViewItem from mainWindow
TreeViewItem locations = mainWindow.TreeViewItem;
//Passes to function -- checks for DUPLICATE locations
CheckForDuplicate(TreeViewItem.Items, textBox1.Text);
//if Duplicate exists -- warn user
if (isDuplicate == true)
MessageBox.Show("Sorry, the number you entered is a duplicate of a current node, please try again.");
else //else -- create node
{
//Creates TreeViewItems for Location
TreeViewItem newNode = new TreeViewItem();
//Sets Headers for new locations
newNode.Header = textBox1.Text;
//Add TreeView Item to Locations & Blocking Database
mainWindow.TreeViewItem.Items.Add(newNode);
}
}
}
//Checks to see whether the header entered is a DUPLICATE
private void CheckForDuplicate(ItemCollection treeViewItems, string input)
{
for (int index = 0; index < treeViewItems.Count; index++)
{
TreeViewItem item = (TreeViewItem)treeViewItems[index];
string header = item.Header.ToString();
if (header == input)
{
isDuplicate = true;
break;
}
else
isDuplicate = false;
}
}
谢谢你。