Why I might want to do drag and drop without moving mouse? Well, unit tests - good enough? Anyhow. Today I'll explain quick way to drag&drop from code. Let's create a window with button and textbox. When the button clicked I'll put into D&D bag some string and then put it into textbox by subscribing to Drop event.
<StackPanel>
<Button Click="put">Put</Button>
<TextBox Name="box"></TextBox>
</StackPanel>
And code
public Window1()
{
InitializeComponent();
Drop+=new DragEventHandler(onDrop);
}
void put(object s, RoutedEventArgs e)
{
DataObject o = new DataObject();
o.SetData("kuku");
}
void onDrop(object sender, DragEventArgs e)
{
box.Text = e.Data.GetData(DataFormats.StringFormat).ToString();
}
Well done. Now I should call Ole DragFinish? But hrr, first get handler of my control.. Hr... NO WAY! I'll use DragDrop.DoDragDrop static method. It'll do all the rest. So change put method to something like this to get a result you're waiting for
void put(object s, RoutedEventArgs e)
{
DataObject o = new DataObject();
o.SetData("kuku");
DragDrop.DoDragDrop(this, o, DragDropEffects.All);
}
We done.
No comments:
Post a Comment