There is a "field" on which some items are draggable:
Here is a XAML code:
<Canvas Height="180" Width="169" >
<Image Canvas.Left="0" Canvas.Top="0" Height="180" Width="149"
Source="../Picts/field.png" />
<Pages:FieldItem x:Name="Item2" Canvas.Left="129" Canvas.Top="34"
MouseLeftButtonDown="Item1_OnMouseLeftButtonDown"
MouseLeftButtonUp="Item1_MouseLeftButtonUp"
MouseMove="Item1_MouseMove"
/>
</Canvas>
And code-behind:
private bool bIsCaptured = false;
double mouseVerticalPosition;
double mouseHorizontalPosition;
private void Item1_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
((FrameworkElement)sender).CaptureMouse();
bIsCaptured = true;
mouseVerticalPosition = e.GetPosition(null).Y;
mouseHorizontalPosition = e.GetPosition(null).X;
}
private void Item1_MouseMove(object sender, MouseEventArgs e)
{
if (bIsCaptured)
{
UserControl item = sender as UserControl;
if (item != null)
{
// Calculate the current position of the object.
double deltaV = e.GetPosition(null).Y - mouseVerticalPosition;
double deltaH = e.GetPosition(null).X - mouseHorizontalPosition;
double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);
// Set new position of object.
item.SetValue(Canvas.TopProperty, newTop);
item.SetValue(Canvas.LeftProperty, newLeft);
// Update position global variables.
mouseVerticalPosition = e.GetPosition(null).Y;
mouseHorizontalPosition = e.GetPosition(null).X;
}
}
}
private void Item1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
UserControl item = sender as UserControl;
bIsCaptured = false;
if (item != null)
{
item.ReleaseMouseCapture();
}
}
My task is to display a collection of items that are bound to a list of object. How to do that is described in the topic: http://stackoverflow.com/questions/3508699/silverlight-4-how-to-display-list-of-custom-controls-not-in-list-order.
The only lack of the suggested approach is: items are not draggable anymore...
Here if update XAML code of controls "holder" (provided for consistency purposes):
<Canvas Height="180" Width="169" Background="Beige" HorizontalAlignment="Center" >
<Image Canvas.Left="0" Canvas.Top="0" Height="180" Width="149"
Source="../Picts/field.png" />
<Pages:MyItemsControl ItemsSource="{Binding SquadFieldPlayers}">
<Pages:MyItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Height="180" Width="169" Background="Transparent"
HorizontalAlignment="Center" />
</ItemsPanelTemplate>
</Pages:MyItemsControl.ItemsPanel>
<Pages:MyItemsControl.ItemTemplate>
<DataTemplate>
<Pages:FieldItem
MouseLeftButtonDown="Item1_OnMouseLeftButtonDown"
MouseLeftButtonUp="Item1_MouseLeftButtonUp"
MouseMove="Item1_MouseMove"
/>
</DataTemplate>
</Pages:MyItemsControl.ItemTemplate>
</Pages:MyItemsControl >
</Canvas>
All mouse-event handlers are called, but items are not really movable... why?