In my program I have a tabItem
that gets selected when a TreeViewItem
with an equivalent header
is selected.
This is what I curre
Firstly, you have to get the parent node and the number contained in its header:
TreeViewItem parentItem = (TreeViewItem)selectedItem.Parent;
int curNumber = getNumber(parentItem.Header.ToString());
getNumber
is a function to retrieve the number from its exact location in the parent node header. You have to tell more about that in order to write a proper function; for the time being, just the basics (it extracts all the numbers in the input string):
private int getNumber(string parentNodeHeader)
{
int curNumber = 0;
//Required string-analysis actions
//Sample functionality: extract all the numbers in the given string
string outString = "";
int count = -1;
do
{
count = count + 1;
Char curChar = Convert.ToChar(parentNodeHeader.Substring(count, 1));
if (Char.IsNumber(curChar))
{
outString = outString + parentNodeHeader.Substring(count, 1);
}
} while (count < parentNodeHeader.Length - 1);
if (outString != "")
{
curNumber = Convert.ToInt32(outString);
}
return curNumber;
}
And then you have to update the query to account for the new information:
.OfType<TabItem>().SingleOrDefault(n => n.Header.ToString() == selectedItem.Header.ToString() + curNumber.ToString());
UPDATE
The function above just shows the kind of code I usually rely on; but for simple situations (like the proposed one of getting all the numbers in a string), you might prefer to rely on Regex
, as suggested by Viv. You might rely on something on the lines of:
private int getNumber(string parentNodeHeader)
{
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(parentNodeHeader, @"\d+");
return Convert.ToInt32(m.Value);
}
This function only delivers the first set of consecutive numbers it finds; different result than the function above but enough as a proof of concept (intention of this answer).