samedi 30 janvier 2010

Multi Selection TreeView in WPF, the easy way...

I was losing my precious coding time to implement a feature microsoft could do themselves... It's their fault if Genuilder is late ! :p

By the way here is how to use it.
In this example I define an implicit syle for TreeViewItem which set the border in gray when it is selected.




<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="BorderThickness" Value="1"></Setter>
<Style.Triggers>
<Trigger Property="c:TreeViewExtensions.IsSelected" Value="True" >
<Setter Property="BorderBrush" Value="Gray"></Setter>
</Trigger>
</Style.Triggers>
</Style>

...

<TreeView c:TreeViewExtensions.EnableMultiSelect="true"
c:TreeViewExtensions.SelectedItems="{Binding SelectedItems}"
ItemsSource="{Binding Items}"
... />




Here is the TreeViewExtension :


And the sample app :

6 commentaires:

  1. Hi Nicolas,

    Nice approach. But the selectedItems are not in sync when a drop has occured.

    This is a workaround. It works, but isn't perfect (as the reset isn't performed inmediately but with the first next selection).

    1. Add the following code to EnableMultiSelectChanged:
    tree.AddHandler(TreeView.PreviewDropEvent, new DragEventHandler(PreviewDrop)); (also a RemoveHandler)

    2. Add the following code to the class:
    private static bool possibleDropOccurred = false;
    static void PreviewDrop(object sender, DragEventArgs e)
    {
    // Reset the SelectedItems when a drop takes place
    possibleDropOccurred = true;
    }

    3. Change RealSelectedChanged:
    {
    TreeViewItem item = (TreeViewItem)sender;
    var selectedItems = GetSelectedItems(GetTree(item));
    if (selectedItems != null)
    {
    if (possibleDropOccurred)
    {
    selectedItems.Clear();
    possibleDropOccurred = false;
    }
    var isSelected = GetIsSelected(item);
    .....

    Thanks,

    Frank
    RépondreSupprimer
  2. Lets have a look also here: http://dotnetlearning.wordpress.com/2010/10/14/multi-selection-tree-view/
    RépondreSupprimer
  3. If I try to change the background on a item by modifying the style, when a parent is selected, visually all of the children are selected too. How do I fix this?
    RépondreSupprimer
  4. Ce commentaire a été supprimé par l'auteur.
    RépondreSupprimer
  5. https://connect.microsoft.com/WPF/feedback/details/654579/treeview-multiselect-and-two-way-binding-out-of-the-box
    RépondreSupprimer
  6. Hi,

    The reason I’m writing this email is to see if we can get a license for the "Multi Selection TreeView in WPF" since we couldn’t find any license published by you.
    We would like to use the software in one of our commercial product.

    If you have any commercial license or willing to confirm to us that this can be distributed under different license (preferably BSD) – it would be much appreciated.

    Thank you
    RépondreSupprimer