.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Post New Web Links

Panning Canvas in WPF using C#

Posted By:      Posted Date: October 21, 2010    Points: 0   Category :WPF

Here I need to apply panning to my canvas.... I have tried the same TranslateTransform as in case of image panning but i got some unexpected behavior... my code is as follows....

        void MyCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)





        void MyCanvas_MouseMove(object sender, MouseEventArgs e)


            if (!MyCanvas.IsMouseCaptured)



            var t = (TranslateTransform)((TransformGroup)MyCanvas.RenderTransform).Children.First(tr => tr is TranslateTransform);


            Vector v = start - e.GetPosition(MyCanvas);

            t.X = origin.X - v.X;

            t.Y = origin.Y - v.Y;



        void MyCanvas_MouseLeftButtonDown(object sender, MouseButtonEvent

View Complete Post

More Related Resource Links

How to customize workflow canvas in re-host environment?

Hi there,  Currently I'm developing a re-hosted debugger for Windows Workflow.  For the workflow canvas, I'm using View property of WorkflowDesigner class and bind my ContentControl to it.  The question here is, how to customize the WorkflowDesigner.View? Examples of customization are:   Extract the overview window, so that I can put the window in another part of the UI Change the zoom tool into the slide bar as in MS Word.   Thanks and best regards,  Arinto

Saving Canvas and other UIElements as embedded resource

Hi All, I am trying to save a canvas and its content as an embedded resource to another assembly but in doing so I got a Non-Serializable exception. Is there a better way of doing this? Here is the code I used in embedding the Canvas: // create an assembly AssemblyName assemblyName = new AssemblyName(System.IO.Path.GetFileNameWithoutExtension(filename)); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll"); // create a class TypeBuilder typeBuilder = moduleBuilder.DefineType("ModuleName", TypeAttributes.Public, typeof(EmbeddedBAML)); // Create a default constructor ConstructorBuilder constuctorDefault = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); ILGenerator ilGenerator = constuctorDefault.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Call, typeof(EmbeddedBAML).GetConstructor(Type.EmptyTypes)); ilGenerator.Emit(OpCodes.Ret); typeBuilder.CreateType(); IResourceWriter resourceWriter = assemblyBuilder.DefineResource(assemblyName.Name + ".canvas", "Contains the Canvas object",assemblyName.Name + ".canvas", ResourceAttributes.Pu

usercontrol layout in canvas at runtime puts in mult. copies of 1st element in collection.

I created a usercontrol which has a few DP's that match up with fields in a sql table. The requirements of this control specify if I get a specific status value I will flash the usercontrol to draw attention to a specific area of equipment in the facility. I also provide a tooltip which has all the fields of data to view. The usercontrol should only display it's description. On a button click I run the following code which instantiates a new observablecollection of my custom usercontrol (I call it profiNode). It then fills a dataset by calling our DAL and then I loop through the datarows using the values to create a new profiNode object for each row. I then add these to the observable collection, but I suppose a generic list would work too.     ProfiNodes = new ObservableCollection< profi.profiNode > (); DataSet data = new DataSet(); data = this.DataLayer.getDataSet("Select * from ProfibusMapping", CommandType.Text, null); foreach (DataRow row in data.Tables[0].Rows) { profi.profiNode node = new profi.profiNode((string)row.ItemArray[0],(int)row.ItemArray[1], (int)row.ItemArray[2], (int)row.ItemArray[3], (string)row.ItemArray[4], (DateTime)row.ItemArray[5], (int)row.ItemArray[6], (int)row.ItemArray[7], (string) row.ItemArray[8], (double)row.ItemArray[9], (double)row.ItemArray[10]); node.ID = string.Format("node_M{0}_A{1}&q

how to create property widget and change the properties of dragged-dropped UIelement in canvas in wp

I'm new in WPF development. I'd like to learn it. I'm curious and having problem in developing property widget for the UIElements. I want to change the properties of the dragged and dropped UIElement from the Property widget. How could I do this? I'd glad if any help is suggested. I've listbox and canvas. Elements from listbox can be dropped to the canvas. I'm trying to change the properties of the dropped element through a property widget. I don't know how to do this. I'd be grateful to any kind of support.   Regards, Binaya

different mouseWheel handlers for canvas and image

i have different mouse wheel handler for both canvas and image in that canvas,,but when i move my mouse over image and roll the wheel then the canvas mousewheel handler also starts working,,here is my code:   void img_MouseWheel(object sender, MouseWheelEventArgs e) { if (e.Delta > 1) { ((Image)sender).Width =((Image)sender).ActualWidth*1.01; ((Image)sender).Height = ((Image)sender).ActualHeight*1.01; } if (e.Delta < 1) { ((Image)sender).Width = ((Image)sender).ActualWidth/1.01; ((Image)sender).Height =((Image)sender).ActualHeight/1.01; } } <pre lang="x-c#">void mycanvas_MouseWheel(object sender, MouseWheelEventArgs e) { if (e.Delta > 1) { ((Canvas)sender).Width = ((Canvas)sender).ActualWidth*1.01; ((Canvas)sender).Height = ((Canvas)sender).ActualHeight*1.01; foreach(UIElement myElement in ((Canvas)sender).Children) { if (myElement is Image) { Image myimage = myElement as Image; myimage.Width *= 1.01 ; myimage.Height *= 1.01; } } } if (e.Delta < 1) { ((Canvas)sender).Width = ((Canvas)sender).ActualWidth /1.01; ((Canvas)sender).Height = ((Canvas)sender).ActualHeight/1.01; foreach (UIElement myElement in ((Canvas)sender).Children) { if (myElement is Image) { Image myimage = myElement as Imag

Is there a method that returns the control's type, such as "TextBox", "TextBlock", "Canvas", etc.,

Hello, I have a method that is passed in a FrameworkElement Ctrl.  When I use Ctrl.GetType().ToString() I get "System.Window.Controls.TextBox" or another string if a different type of control is passed in.  All I am interested in is the text after the last dot/period.  In my searching I thought I came across something that just returned the portion I'm looking for, but now can't find it. Is there a method that returns the control's type, such as "TextBox", "TextBlock", "Canvas", etc., without its parents? Regards, Robert

Items data binding in Canvas

Hello! I have an ObservableCollection, which contains points with X and Y coordinates. I need to bind this ObservableCollection to Canvas control, but there is no way to bind collection directly to Canvas. I found a few samples with ItemsControl (and ListBox). <Canvas x:Name="Root"> <ItemsControl ItemsSource="{Binding AllObjects}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Canvas.Left" Value="{Binding Longitude}" /> <Setter Property="Canvas.Top" Value="{Binding Latitude}" /> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate DataType="{x:Type o:OperationPoint}"> <Ellipse Width="3" Height="3" Fill="Blue" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Canvas> It works, but there are many elements in visual tree I don't need: Canvas (Root) ItemsControl Border ItemsPresenter Canvas ContentPresenter Ellipse ContentPresenter

Ink Canvas or Ink Presenter



I need to load the jpeg image into asp.net page and allow the users to draw some sketches on the image and save the image with the sketches. I am able to do it using WPF Ink Canvas in Windows application but I really not sure how can I achieve the same in ASP.NET web application. Please can anyone throw some ideas on this.




How I can get coordinate textbox carete in Canvas.

Hi !
I have following xaml:

<UserControl x:Class="Dev1.Pronto.AD4.Modules.AdProcessing.Views.AdTextView"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <Label Content="MyLabel"/>

Move all children on canvas or preferrably move the entire canvas



I´m working on a small app that parses the gpx file from the GPS. It will animate how me and my dog moves when we go hunting. I want to zoom in so that I can analyse how the dog is working and therefore need the graph to scroll and keep my position centered.

Yesterday I used a Canvas and plotted my points as black rectangles and the dog as red rectangles. Then used the SetLeft and SetTop to scroll the Canvas. I then added a polyline connecting the dogs points but didnt find StLeft and SetTop for the polyline. Played around with RenderTransform but never got it working.

1. My question is is canvas suitable for this?

2. Is there a way to move the entire canvas and all its children in one command?

3. Is there a generic way that can be used to move all UIElements.

By move I mean move relative an element relative to its current position, for example 2 pixels left and 5 pixels up.



Trying to learn

Image Scroll and Panning


im using ASP.net 2005 

 i'm search at specific position in image when the image is zoom in

i'm make a search for specific location name and i get it and draw a circle for the location,

but the problem is to make panning the cursor to the location when i press the button search

 can any one help me please




Silverlight user control, canvas "layout root", no key events ever.



I'm trying to use a UserControl in Silverlight and I want to handle some key events. The user control is a network diagram, laying out data points in a circle and showing the relations between points. It consists of a canvas to which various shapes (ellipses for data points, lines for relations between points). I'd like it to be focusable and receive mouse and keyboard events to add support for things like rotation, scaling, and randomizing the layout of data points (how readable the diagram is depends on the data and where in the circle related data points are located, but I'm not going to attempt any smart layout logic that figures out where to put the points; instead, I simply allow the points to be laid out in random order along the circle); I was thinking F5 (with it's "reload/refresh" connotations) would be a neat key for this.

Trouble is, I am never ever receiving any key events. Mouse events apparently do bubble up to the canvas, but only from labels - the data points have labels - so I can handle them there. Currently this allows me to resize and rotate the diagram by scrolling the mouse wheel (with the shift key down to rotate, without to scale) if and only if the mouse cursor is over a label. Not *quite* what I want!

After some quick googling I've attempted to set IsTabStop to true on the UserControl containing the Canva

Removing buttons from canvas


I'm working with Visual Studio 2008 and I have created a window with a Canvas in a ScrollViewer. On the canvas, I've placed an image and the code I've written places buttons on the canvas at certain locations. So far, so good, but I'm also trying to delete certain buttons that have a certain content. My method looks like this:


 RemoveDataPointFromVisualization(DataPoint dp)
 content = generateContent(dp);

 (Button btn in
 (btn.Content == content)
  } } }

I think my problem lies with the loop, as I don't know for sure if this is correct; does it loop over all the buttons that are children of the canvas? If that works, the contents of the button, which have been generated by generateContent(), are compared to the content that is generated the moment this method is called.

What do I do wrong?


To provide some more information: every time I execute my program, it displays this er

Zooming in/out on canvas: how to leave some children unscaled?


I'm working with Visual Studio 2008 and I have created a window with a Canvas in a ScrollViewer. On the canvas, I've placed an image and the code I've written places buttons on the canvas at certain locations. So far, so good, but I'm trying to implement a zooming method which scales the canvas and the image, but leaves the buttons intact in terms of size and content -- however, their location should scale together with the image and the canvas.
What I have thusfar is this:

private void zoomIn(Object sender, MouseButtonEventArgs e)
  mapCanvas.Width *= ZoomFactor;
  mapCanvas.Height *= ZoomFactor;
  Zoom *= ZoomFactor;
  TransformGroup transform = new TransformGroup();
  transform.Children.Add(new ScaleTransform(Zoom, Zoom));
  transform.Children.Add(new TranslateTransform(0, 0));
  mapCanvas.RenderTransform = transform;

This, together with an analogue zoomOut method, works like a charm, but the buttons are scaled as well, obviously because RenderTransform is applied to every child of the canvas as well.

My question is: how can I leave the buttons unscaled?

Resize dynamically created controls on Canvas



This is my first thread on this forum and i'm a beginner on WPF.

After google-ing for long time, it seems I can't find a solution for my problem.

I'm working on WPF form. The form contains a canvas and I create Labels on the Canvas dynamically at run-time.

First I had a problem to move the control on the canvas, but eventually I solved this problem by using a class implemented by Josh smith from

his article on codeproject.com. Now, I can move my lables freely on the Canvas.

But now, I want to resize the labels width or height that are created at run-time.

I changed the cursor of the mouse to (horizontal scroll or Vertical scroll) when it touched when of the edges of the label.

but I can't find how to implement the resizing when the mouse goes down or pressed to stretch the label.

Many tutorials found on the web talks about resizing controls the are previously declared in xaml and I want to implement it at code-behind.

Can please help me.

Thanks for help in advance.

Why would a control not respond to mouse clicks when added to a custom canvas


   I have a custom UserControl that contains a grid and toolbar.  When I add this control to a custom drag canvas, it does not respond to MouseClick events.
   I suspected the custom drag panel as it overrides UIElement.OnPreviewMouseLeftButtonDown and sets e.Handled = true but commenting out line that sets e.Handled to true does not allow control process mouse clicks.
   If, however, I derive my custom control from Popup, it sees mouse clicks as toolbar button commands are executed. 
   What am I observing?

Setting the canvas height and width to Grid size


I have a canvas and I have it set to the following attributes


 Grid.Row="1" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="2"


However I want the canvas height and width to fill those locations. Also upon window resize i want the canvas height and width to adjust accordingly.

Any ideas? Thanks all

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend