This is an old revision of the document!
Drag and Drop
Source Control (Drag Origin)
Sample ListBox (XAML) where Drag originates:
<ListBox Name="lstEnvironments" SelectionChanged="lstEnvironments_SelectionChanged" PreviewMouseLeftButtonDown="lstEnvironments_PreviewMouseLeftButtonDown" MouseMove="lstEnvironments_MouseMove"> <ListBoxItem>Normal</ListBoxItem> <ListBoxItem>Restaurant/Party</ListBoxItem> <ListBoxItem>Telephone</ListBoxItem> <ListBoxItem>Music</ListBoxItem> </ListBox>
Target Control (Drop Target)
Target controls where Drop is performed. In this case, a ListBox
, TextBlock
, and TextBox
.
<TextBlock FontWeight="Bold" Margin="0,10,0,0">Dragged Items</TextBlock> <TextBlock>ListBox:</TextBlock> <ListBox Name="lstAppliedEnvironment" AllowDrop="True" Height="100" SelectionMode="Single" DragEnter="lstAppliedEnvironment_DragEnter" Drop="lstAppliedEnvironment_Drop"> </ListBox> <StackPanel Orientation="Horizontal"> <TextBlock>TextBlock:</TextBlock> <TextBlock Name="lblAppliedEnvironment" Margin="5,0,0,20" AllowDrop="True" DragEnter="lblAppliedEnvironment_DragEnter" Drop="lblApliedEnvironment_Drop">Value</TextBlock> </StackPanel> <TextBox Name="txtAppliedEnvironment" Height="30" AllowDrop="True" DragEnter="txtSelectedEnvironment_DragEnter" Drop="txtAppliedEnvironment_Drop">Test 2</TextBox>
Code behind:
private void lstAppliedEnvironment_DragEnter(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent("str") || sender == e.Source) { e.Effects = DragDropEffects.None; } } private void lstAppliedEnvironment_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(string))) { string str = e.Data.GetData(typeof(string)) as string; ListBox lstBox = sender as ListBox; lstBox.BeginInit(); lstBox.Items.Add(str); lstBox.EndInit(); lstEnvironments2.BeginInit(); lstEnvironments2.EndInit(); } } private void lblAppliedEnvironment_DragEnter(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent("str") || sender == e.Source) { e.Effects = DragDropEffects.None; } } private void lblAppliedEnvironment_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(string))) { string str = e.Data.GetData(typeof(string)) as string; TextBlock lbl = sender as TextBlock; lbl.Text = str; } }