BinaryMee
BinaryMee

Reputation: 2142

Copy Treeview selected Item WPF

I have a Treeview in my WPF application. I need to copy the elements in my treeview.

private void copyCmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    // Set text to clip board 
    TreeView tvi = (TreeView)sender;
    Clipboard.SetText(tvi.SelectedValue.ToString());
}

But here the tvi.SelectedValue wouldn't return the text which i selected in my treeview. How can i get the text value i selected in my treeview.

Update:

<TreeView Grid.Column="0" Grid.Row="0"  
          HorizontalAlignment="Stretch" Name="treeView1" 
          SelectedItemChanged="treeView1_SelectedItemChanged">
    <TreeView.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Copy" 
                        Executed="copyCmdBinding_Executed" 
                        CanExecute="copyCmdBinding_CanExecute"/>
    </TreeView.CommandBindings>
    //Tree elements
</TreeView>

Upvotes: 0

Views: 2802

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

try this:

((TreeViewItem)tvi.SelectedItem).Header.ToString())

in general this code may be useful:

((T1)tvi.SelectedItem).P.ToString()) 
// T1: type of property that is binded, 
// P: proper method or property that hold the string content

Upvotes: 1

Natxo
Natxo

Reputation: 2947

Items in your tree can be of any type, and SelectedValue returns the Value of the property specified by SelectedValuePath of the SelectedItem. So, make sure you have set SelectedValuePath in the Treeview!

Upvotes: 0

Related Questions