How do I get ListBox, Canvas and Thumb to work together?
I am attempting to reuse the selection logic of ListBox together with a Canvas that contains draggable Thumbs.
Unfortunately the Thumb appears to handle the mouse events so that clicking on the Thumb doesn't make the item selected.
I was hoping these elements could be made to work together without resorting to workarounds in procedural code. If anyone knows if this is possible or how to do it please advise me.
Code examples follow.
In the XAML I define the ListBox and specify a Canvas as the ItemsPanel:
<Window x:Class="ListBoxCanvasThumb.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
Loaded="Window_Loaded"
>
<Grid>
<ListBox
x:Name="listBox"
>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
</Window>
In the Loaded event handler I create a draggable Thumb, wrap it in a ListBoxItem, set the positon in the Canvas and then add it to the ListBox:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Thumb t = new Thumb();
t.Width = 10;
t.Height = 10;
t.DragDelta += new DragDeltaEventHandler(thumb_DragDelta);
ListBoxItem i = new ListBoxItem();
Canvas.SetLeft(i, 10);
Canvas.SetTop(i, 10);
i.Content = t;
listBox.Items.Add(i);
}
In the DragDelta event handler I update the position of the item in the Canvas:
void thumb_DragDelta(object sender, DragDeltaEventArgs e)
{
ListBoxItem i = (ListBoxItem)((Thumb)sender).Parent;
Canvas.SetLeft(i, Canvas.GetLeft(i) + e.HorizontalChange);
Canvas.SetTop(i, Canvas.GetTop(i) + e.VerticalChange);
}