Monday, August 4, 2008

Handle Copy/Paste in Hierarchical TreeView

I’m starting to get my head wrapped around the WPF / XAML paradigm, and hadn’t come across too many examples of Copy/Paste functionality so I thought I would share my recent discovery of the ApplicationCommands class.  With it, adding a CommandBinding to receive Copy events for a control like TreeView is trivial.

Private Sub MainWindow_Loaded(sender As System.Object,
    e As System.Windows.RoutedEventArgs) Handles MainWindow.Loaded

 ' Handle Copy/Paste function

 Dim cb As New CommandBinding(ApplicationCommands.Copy,
    AddressOf TableList_Copy)


End Sub


Private Sub TableList_Copy(ByVal sender As Object,
    ByVal e As ExecutedRoutedEventArgs)

  Dim selectNode As Object = TableList.SelectedValue

  If TypeOf selectNode Is DbTable Then

    Clipboard.SetText(CType(selectNode, DbTable).TableName)


    Clipboard.SetText(CType(selectNode, Column).Name)

  End If

End Sub

My TreeView is bound to a HierarchicalDataTemplate that can contain a collection of Column objects, hence the need to check the type of the TableList.SelectedValue

<TreeView Margin="19,57,0,28" Name="TableList"
="Left" Width="286"
ItemsSource="{Binding Path=.}"
="{StaticResource TableListTemplate}" />



  <DataTemplate x:Key="TableTemplate">


      <TextBlock Text="{Binding Path=Name}" />


      <TextBlock Text="{Binding Path=Type}" />





  <HierarchicalDataTemplate x:Key="TableListTemplate"

   ItemsSource="{Binding Path=ColumnList}"

    ItemTemplate="{StaticResource TableTemplate}" >

     <TextBlock Text="{Binding Path=TableName}" />





No comments: