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 :

1 commentaires:

frank a dit…

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

Enregistrer un commentaire