Drag and drop in WPF (and similar to Silverlight)
Many game types use drag and drop, shape selection, memory, as well as other learning games, also other games use drag and drop to allow purchases of powers, power-ups, etc. Here is a simple process of dragging and dropping. It is presented here to for you to get started.
In a WPF Application (I named mine, WPFDragDropExample), replace the <Grid> with the following:
<Canvas>
<Ellipse Name="greenie" Height="50" Width="50" Fill="Green"
AllowDrop="True"
Drop="ellipse_Drop"
Canvas.Left="195"
Canvas.Top="143" />
<TextBox Background="Azure" Height="50" Width="50" Text="Blue"/>
</Canvas>
In this a circular ellipse is set up AllowDrop and an event that will accept a Drop (event name: ellipse_Drop )
Now you need to add code to the code behind which is: MainWindow.xaml.cs
Add the following event method:
//*******************Start copy here *******************
private void ellipse_Drop(object sender, DragEventArgs e)
{
Ellipse ellipse = sender as Ellipse;
if (ellipse != null)
{
// If the DataObject contains string data, extract it.
if (e.Data.GetDataPresent(DataFormats.StringFormat))
{
string dataString = (string)e.Data.GetData(DataFormats.StringFormat);
// If the string can be converted into a Brush,
// convert it and apply it to the ellipse.
BrushConverter converter = new BrushConverter();
if (converter.IsValid(dataString))
{
Brush newFill = (Brush)converter.ConvertFromString(dataString);
ellipse.Fill = newFill;
}
}
}
}
//*************End copy here ***********************
Now press F5 to run your code, select the word “Blue” in the textbox and drag it over to the ellipse, the ellipse will change to the color blue, in some configurations of the mouse settings you may need to click the primary mouse button (usually the left button) to make the drop complete.
Now type red in the textbox and drag it over to the ellipse, it will change colors again.
Kind of cool if you haven’t done this before. You can do more with this by adding an icon for the drag from the textbox, etc.
Have fun.