Programmatically generated image doesnt have a CanvasLeft
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 Tex开发者_如何学运维tCompositionEventHandler(DragMe_TextInput);
newItem.LostMouseCapture += new MouseEventHandler(DragMe_LostMouseCapture);
RootCanvas.Children.Add(newItem);
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.
精彩评论