I have a ListBox and a DockPanel. List box contains items that are supposed to be dragged onto the dock panel. I've implemented that by following this link.
There are a couple of things I do not understand though:
While dragging, all I see is a cursor. I'd like to literary see the list item I am
dragging to move around with my cursor. How do I do that?
Is the DragDropEffect property only for the different cursor design or it has a
higher purpose? :)
How do I make list item disappear from the ListBox once it is dropped onto the
DockPanel?
I'd like to enforce some animation on the items that I drag, like glow once it is
dropped. Which trigger/setter should I use for that?
Here's my code for basic dragging and dropping:
Code-behind for the ListBox part
private Point startPosition;
private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPosition = e.GetPosition(null);
}
private void ListBox_PreviewMouseMove(object sender, MouseEventArgs e)
{
Point currentPosition;
Vector offset;
ListBox listBox;
ListBoxItem item;
Match match;
DataObject dragData;
currentPosition = e.GetPosition(null);
offset = startPosition - currentPosition;
if (e.LeftButton == MouseButtonState.Pressed &&
(Math.Abs(offset.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(offset.Y) > SystemParameters.MinimumVerticalDragDistance))
{
// Get the data binded to ListBoxItem object, which is "match"
listBox = sender as ListBox;
item = FindAnchestor<ListBoxItem>((DependencyObject)e.OriginalSource);
match = (Match)listBox.ItemContainerGenerator.ItemFromContainer(item);
dragData = new DataObject("match", match);
DragDrop.DoDragDrop(item, dragData, DragDropEffects.Move);
}
}
Code-behind for the DockPanel part
private void DockPanel_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("match") ||
sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
private void DockPanel_Drop(object sender, DragEventArgs e)
{
Match match;
DockPanel matchSlot;
ContentPresenter contentPresenter;
Binding binding;
if (e.Data.GetDataPresent("match"))
{
match = e.Data.GetData("match") as Match;
matchSlot = sender as DockPanel;
contentPresenter = new ContentPresenter();
contentPresenter.ContentTemplate = this.FindResource("MatchTemplate") as DataTemplate;
binding = new Binding();
binding.Source = match;
contentPresenter.SetBinding(ContentPresenter.ContentProperty, binding);
matchSlot.Children.Clear();
matchSlot.Children.Add(contentPresenter);
}
}
Thanks for all the help.
Ok, after a while I found some answers and discovered a few things on my own.
As for the DragDropEffect enum, it should be used for two reasons:
To distinguish if the item is moved or copied in the code. It serves like a flag and should be used most commonly like this:
if (e.DragDropEffect == DragDropEffect.Move)
{
...
}
else ...
To decorate the mouse cursor based on the enum value. This way it tells the user if he or she is moving or copying the item.
As for the drag and drop visualization here's a link to the post containing the reference which is an excellent starting point for drag and drop to build on: WPF Drag & Drop: How to literally drag an element?
Related
Just wanted to know if its possible to do it like winform? Where i can add a button to where i last click. I tried googling but dont think i found anything similar. Will the grid for WPF be an issue where i can place my button freely on click?
Idea is to click on the coordinate and then press the button to add an image/button.
Below is what i did so far, havent added the button function yet, just wanted to know if its possible to do it as i have done so for winform before.
public MainWindow()
{
InitializeComponent();
MainWindow.xCoord = -1;
MainWindow.yCoord = -1;
}
private void AddEvent_Click(object sender, EventArgs e)
{
if (MainWindow.xCoord < 0 || MainWindow.yCoord < 0)
{
MessageBox.Show("Please select a coordinate");
return;
}
}
public void MainWindow_Mouseup(object sender, MouseEventArgs e)
{
Point p = e.GetPosition(this);
textBox1.Text = "x-" + p.X + "y- " + p.Y;
MainWindow.xCoord = (int)p.X;
MainWindow.yCoord = (int)p.Y;
}
Yes you can do it, and you would need to use a Canvas to draw the button. This can be contained inside the Grid, but AFAIK the Canvas is the only way to have a sort of "Draw" function with UI Controls.
You will want to capture the MouseUp event within the Canvas and then add your button at the location you can retrieve in the Handler.
XAML:
<Grid>
<Canvas x:Name="ButtonCanvas" MouseUp="ButtonCanvas_MouseUp"/>
</Grid>
Code Behind:
private void ButtonCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
Point p = e.GetPosition(ButtonCanvas);
textBox1.Text = "x-" + p.X + "y- " + p.Y;
MainWindow.xCoord = (int)p.X;
MainWindow.yCoord = (int)p.Y;
}
Then just have a function that will create and add a Button at these coordinates (I will assume you have some sort of "Add Button to Canvas" Button):
private void AddButtonToCoord_Click(object sender, EventArgs e)
{
var button = new Button();
//--change button properties if you want--
//add to canvas
Canvas.Childen.Add(button);
//set Control coordinates within the canvas
Canvas.SetLeft(button, MainWindow.xCoord);
Canvas.SetTop(button, MainWindow.yCoord);
}
You can get fancier for your needs, like if you want the center of the button to be at the Coordinates, or if you want to prevent the Button from being drawn outside the canvas (like if the user click the very bottom right corner). But this should be enough to get a minimum working example.
I have code where I can take a look at the SelectedItem and then output ToString() to get the record into the clipboard.
How can I detect what cell the user is right clicking on in order to copy just that cell in the SelectedItem?
For example, if I have Borrower Information and the user right-clicks on last name, I would like to give the ability to just copy last name to clipboard.
Thank you!
UPDATE:
Here is the code that I used as suggested by Josh, it worked great:
private void BorrowerInfoCopyClicked(object sender, RoutedEventArgs e)
{
BorrowerViewModel vm = this.DataContext as BorrowerViewModel;
if (vm != null)
{
Clipboard.SetData(DataFormats.Text, vm.CurrentTextBlockText);
}
}
private void AddressCopyClicked(object sender, RoutedEventArgs e)
{
BorrowerViewModel vm = this.DataContext as BorrowerViewModel;
if (vm != null)
{
Clipboard.SetData(DataFormats.Text, vm.CurrentTextBlockText);
}
}
private void lstViews_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
BorrowerViewModel vm = this.DataContext as BorrowerViewModel;
if (vm != null)
{
if (e.OriginalSource is TextBlock)
{
TextBlock txtBlock = e.OriginalSource as TextBlock;
vm.CurrentTextBlockText = txtBlock.Text;
}
}
}
I've done this by handling the PreviewMouseRightButtonDown event on the ListView and checking if e.OriginalSource is a TextBlock. If so, copy the txtBlk.Text to the clipboard. This code could either be in the code-behind of the View that contains the ListView, or as a behavior you attach to the ListView. If you need to use a context menu to perform the Copy operation, have a TextBlock field that you use to store a reference to the TextBlock, and in your method that responds to a MenuItem's click (or Command execution) reference the TextBlock there instead.
I'm implementing simple drag-and-drop functionality in my app, and I would like to know if the user has dropped the item above the first item in the list (in the header row) so i can just insert it as the first item.
I'm using VisualTreeHelper.HitTest to get the item at the drop position, but this only works if there actually is an item there.
HitTestResult hitTestResults = VisualTreeHelper.HitTest(myListView, location);
When the mouse is on the headers i get one of many several items in hitTestResults.VisualHit. In just a few tests, I've gotten ListBoxChrome, TextBlock, and Border How can i know if any of these are part of the header row? I can't just test for them specifically since there could be other UI elements returned.
Can i get the coordinates of the header row of the listview to see if my point is inside it? Or is there a way that i can know if my Point is inside that header row?
I don't know how your current implementation look but you can walk up the Visual Tree until you either find a ListViewItem or a GridViewColumnHeader. If you find a GridViewColumnHeader you know that the item was dropped in this specific Header.
Uploaded a small sample project here demonstrating the effect with MessageBox's on drop: http://www.mediafire.com/?v3l8nl4rnewhz5s
It will look something like this
private void ListView_Drop(object sender, DragEventArgs e)
{
ListView parent = sender as ListView;
YourDataClass data = e.Data.GetData(typeof(YourDataClass)) as YourDataClass;
if (data != null)
{
HitTestResult hitTestResult = VisualTreeHelper.HitTest(parent, e.GetPosition(parent));
ListViewItem hitItem = VisualTreeHelpers.GetVisualParent<ListViewItem>(hitTestResult.VisualHit);
GridViewColumnHeader columnHeader = VisualTreeHelpers.GetVisualParent<GridViewColumnHeader>(hitTestResult.VisualHit);
if (hitItem != null) // ListViewItem Drop
{
//..
}
else if (columnHeader != null) // Header Drop
{
//..
}
}
}
public static T GetVisualParent<T>(object childObject) where T : Visual
{
DependencyObject child = childObject as DependencyObject;
while ((child != null) && !(child is T))
{
child = VisualTreeHelper.GetParent(child);
}
return child as T;
}
I am creating controls (say button) on a grid. I want to create a connecting line between controls.
Say you you do mousedown on one button and release mouse over another button. This should draw a line between these two buttons.
Can some one help me or give me some ideas on how to do this?
Thanks in advance!
I'm doing something similar; here's a quick summary of what I did:
Drag & Drop
For handling the drag-and-drop between controls there's quite a bit of literature on the web (just search WPF drag-and-drop). The default drag-and-drop implementation is overly complex, IMO, and we ended up using some attached DPs to make it easier (similar to these). Basically, you want a drag method that looks something like this:
private void onMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
if (element == null)
return;
DragDrop.DoDragDrop(element, new DataObject(this), DragDropEffects.Move);
}
On the target, set AllowDrop to true, then add an event to Drop:
private void onDrop(object sender, DragEventArgs args)
{
FrameworkElement elem = sender as FrameworkElement;
if (null == elem)
return;
IDataObject data = args.Data;
if (!data.GetDataPresent(typeof(GraphNode))
return;
GraphNode node = data.GetData(typeof(GraphNode)) as GraphNode;
if(null == node)
return;
// ----- Actually do your stuff here -----
}
Drawing the Line
Now for the tricky part! Each control exposes an AnchorPoint DependencyProperty. When the LayoutUpdated event is raised (i.e. when the control moves/resizes/etc), the control recalculates its AnchorPoint. When a connecting line is added, it binds to the DependencyProperties of both the source and destination's AnchorPoints. [EDIT: As Ray Burns pointed out in the comments the Canvas and grid just need to be in the same place; they don't need to be int the same hierarchy (though they may be)]
For updating the position DP:
private void onLayoutUpdated(object sender, EventArgs e)
{
Size size = RenderSize;
Point ofs = new Point(size.Width / 2, isInput ? 0 : size.Height);
AnchorPoint = TransformToVisual(node.canvas).Transform(ofs);
}
For creating the line class (can be done in XAML, too):
public sealed class GraphEdge : UserControl
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(Point), typeof(GraphEdge), new FrameworkPropertyMetadata(default(Point)));
public Point Source { get { return (Point) this.GetValue(SourceProperty); } set { this.SetValue(SourceProperty, value); } }
public static readonly DependencyProperty DestinationProperty = DependencyProperty.Register("Destination", typeof(Point), typeof(GraphEdge), new FrameworkPropertyMetadata(default(Point)));
public Point Destination { get { return (Point) this.GetValue(DestinationProperty); } set { this.SetValue(DestinationProperty, value); } }
public GraphEdge()
{
LineSegment segment = new LineSegment(default(Point), true);
PathFigure figure = new PathFigure(default(Point), new[] { segment }, false);
PathGeometry geometry = new PathGeometry(new[] { figure });
BindingBase sourceBinding = new Binding {Source = this, Path = new PropertyPath(SourceProperty)};
BindingBase destinationBinding = new Binding { Source = this, Path = new PropertyPath(DestinationProperty) };
BindingOperations.SetBinding(figure, PathFigure.StartPointProperty, sourceBinding);
BindingOperations.SetBinding(segment, LineSegment.PointProperty, destinationBinding);
Content = new Path
{
Data = geometry,
StrokeThickness = 5,
Stroke = Brushes.White,
MinWidth = 1,
MinHeight = 1
};
}
}
If you want to get a lot fancier, you can use a MultiValueBinding on source and destination and add a converter which creates the PathGeometry. Here's an example from GraphSharp. Using this method, you could add arrows to the end of the line, use Bezier curves to make it look more natural, route the line around other controls (though this could be harder than it sounds), etc., etc.
See also
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/dd246675-bc4e-4d1f-8c04-0571ea51267b
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part1.aspx
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part2.aspx
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part3.aspx
http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part4.aspx
http://www.syncfusion.com/products/user-interface-edition/wpf/diagram
http://www.mindscape.co.nz/products/wpfflowdiagrams/
I have two list view on WPF. The first listview is loaded with a Datatable. When double clicking on one item from the first listview, the selectedItem is moved to the second listview.
The problem arises when appears an scroll bar in the first list view due to a lot of elements loaded from the DataTable. If a select one item and double click on the scroll bar down arrow, MouseDoubleClick event is launched and the selected item is moved to the second listview.
How I can detect the double click on the scroll bar to prevent this?
Thanks a lot!
I tested the above code which was very helpful, but found the following to be more stable, as sometimes the source gets reported as GridViewRowPresenter when in fact you are double clicking an item.
var src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);
var srcType = src.GetType();
if (srcType == typeof(ListViewItem) || srcType == typeof(GridViewRowPresenter))
{
// Your logic here
}
Try this in you MouseDoubleClick event on the first Listview:
DependencyObject src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);
if(src is Control && src.GetType() == typeof(ListViewItem))
{
// Your logic here
}
Based on this.
I am using this in various projects and it solves the problem you are facing.
private void ListBox_OnMouseDoubleClick(object pSender, MouseButtonEventArgs pE)
{
FrameworkElement originalSource = pE.OriginalSource as FrameworkElement;
FrameworkElement source = pE.Source as FrameworkElement;
if (originalSource.DataContext != source.DataContext)
{
logic here
}
}
When you have the DataContext you can easy see if the sender is an item or the main listbox
I've got the final solution:
private void ListView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var originalSource = (DependencyObject)e.OriginalSource;
while ((originalSource != null) && !(originalSource is ListViewItem)) originalSource = VisualTreeHelper.GetParent(originalSource);
if (originalSource == null) return;
}
it works for me.