Another issue I found on StackOverflow,which is way more tricky that it seems.
Let’s say we have a Silverlight WP7 application,and we want to add a drag&drop scenario. The user first taps an element,drags his finger to another,and raises his finger on another element. Easy enough! Just handle the MouseLeftButtonDown on each element,store which element triggered the event in a property,handle the MouseLeftButtonUp on each element,and then we have the originator and the destination!
… right?
Well,so I would have thought.
Unfortunately,the MouseLeftButtonUp event will only be triggered if the ‘mouse’ left button (or your finger,sir Claus Jørgensen ;o) )1 is released on the very same control that it was pressed on.
So,if we use this XAML:
1: <Grid x:Name="ContentPanel"
2: Grid.Row="1"
3: Margin="12,12,0"
4: MouseLeftButtonUp="ContentPanel_MouseLeftButtonUp">
5: Grid.RowDeFinitions>
6: RowDeFinition />
7: />
8: </ 9: ="g1"
10: Background="Green"
11: MouseLeftButtonDown="Grid_MouseLeftButtonDown"
12: ="Grid_MouseLeftButtonUp"
13: Tag="dragdrop" 14: ="g2"
15: ="1"
16: ="Blue"
17: 18: 19: 20:
21: Grid>
The layout looks like:
In the MouseLeftButtonUp event handler,we want to paint the destination grid:
2: {
3: var grid = (Grid)sender;
4:
5: grid.Background = new SolidColorBrush(Colors.Red);
6: }
I already encountered a similar issue with Silverlight a few years ago,so I knew about the CaptureMouse method. What is it? Basically it tells a control to keep track of the mouse even if events are triggered outside of the control bounds. Let’s try to use it.
In the MouseLeftButtonDown,simply capture the mouse:
4: }