I need to check what treeviewitem
the user selected everytime it changes. I used the SelectedItemChanged
method or whatever this is called. It works fine but now I need to do a switch case
for every possible treeviewitem
. But I can't do that since I have no idea how to get the name of it. I checked on internet but some people said to use treeview.SelectedItem
but it returns System.Windows.Controls.TreeViewItem Header: Items.Count:0
. I was wondering if I could do that entirely in the .cs code file or if I had to use data binding and such.
Thanks for your help.
EDIT:
Here is how i setup the treeview and the treeviewitems. They are all like the second example.
<TreeView x:Name="treeview" Margin="10,10,0,4" HorizontalAlignment="Left" Width="192" Background="#FFA45353" SelectedItemChanged="treeview_SelectedItemChanged"">
<TreeViewItem IsExpanded="False">
<TreeViewItem.Header>
<StackPanel Orientation="Horizontal">
<Image Source="./Resources/smallicons/icon.jpg"/>
<TextBlock Text=" Main" FontSize="14"/>
</StackPanel>
</TreeViewItem.Header>
<!--==============================================================================================-->
<TreeViewItem>
<TreeViewItem.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="First" Foreground="Black" />
</StackPanel>
</TreeViewItem.Header>
</TreeViewItem>
<!--==============================================================================================-->
Are you looking for this?
TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
string strSelectedNode = selectedNode.Header.ToString();
The above snippet assumes a few things though.
By the way, this code is part of
private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
{
TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
MessageBox.Show(selectedNode.Header.ToString());
}
Ok...As per your treeview and treeview Item setup, you have to code something like this..
private void treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewItem selectedNode = (TreeViewItem)treeview.SelectedItem;
var sp = selectedNode.Header as StackPanel;
var tb = sp.Children[0] as TextBlock;
var selecteditem = tb.Text;
//MessageBox.Show(selecteditem);
switch (selecteditem)
{
case "Main":
MessageBox.Show(selecteditem);
break;
case "First":
MessageBox.Show(selecteditem);
break;
default:
MessageBox.Show("no matching item found");
break;
}
}
Here, I am digging in the selected tree view item to get the Text of selected tree view item. You may have to tweak the code a bit to get it fully operational. Let me know if you need any help with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.