tags:

views:

26

answers:

1

Whilst that title is a slight lie it defines the problem.

I have an image on a WPF Window of which the root element is a Canvas, this image has various event handlers attached to allow me to drag it around the window.

This all works fine, but when I add a new Image to the canvas' children and bind the same event handers the Image does not move.

Now I've traced this (all handlers are binding fine) and it seems that in my MouseDownEvent for some reason the Canvas.GetLeft(((Image)sender)) property is always NaN.

This is the code I am using to create/add the new image:

// Just a class inheriting from Image
DraggableMediaItem newItem = new DraggableMediaItem();

Uri uri = new Uri(ofd.FileName, UriKind.Absolute);
BitmapImage icon = new BitmapImage(uri);
newItem.Source = icon;

newItem.PreviewMouseDown += new MouseButtonEventHandler(DragMe_MouseDown);
newItem.PreviewMouseMove += new MouseEventHandler(DragMe_MouseMove);
newItem.PreviewMouseUp += new MouseButtonEventHandler(DragMe_MouseUp);
newItem.TextInput += new TextCompositionEventHandler(DragMe_TextInput);
newItem.LostMouseCapture += new MouseEventHandler(DragMe_LostMouseCapture);

RootCanvas.Children.Add(newItem);
+1  A: 

For setting Left, Right, Top, Bottom attached properties of Canvas calss you should use Set(side) static methods of Canvas class.

Canvas.SetLeft(newItem, 10d);

More Info at Canvas.SetLeft Method MSDN Article The same is to Right, Top and Bottom properties.

Eugene Cheverda
Thanks I know this I have all the drag/drop stuff working fine for the image drawn on the canvas via XAML but the one added programmatically's onmousedown has no value for it
tigermain
Ah I worked it out via your suggestion. I hadnt realised I needed to set it first
tigermain
FYI: I just added these two additional lines to the above snippet Canvas.SetLeft(newItem, 0); Canvas.SetTop(newItem, 0);
tigermain
So what is the problem? It should work.
Eugene Cheverda
You may set this properties wherever you need. Not only at creating your image. If uiElement will have a Canvas as a parent, then this properties will affect the position of element. Containing in any else parent won't have any effect.
Eugene Cheverda