Canvas zooming in WPF using code behind

Here the scenario is:


I have a canvas with different diagrams drawn on it. Now the requirement is to zoom into the canvas using the code behind either using C# or VB. Moreover I need to place the zoom code in some dll so that i can reuse the same set of code through out my application.

Now my question is how to do this....

I have tried the following code pls have a look..

public MainWindow()
{
    InitializeComponent();

    canvas.MouseEnter += new MouseEventHandler(canvas_MouseEnter);
    canvas.MouseWheel += new MouseWheelEventHandler(canvas_MouseWheel);
}

void canvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
    double height = canvas.ActualHeight;
    double width = canvas.ActualWidth;
    double zoom = e.Delta;
    height += 2;
    width += 2;
    ScaleTransform sc = new ScaleTransform(width, height);
    canvas.LayoutTransform = sc;
    canvas.UpdateLayout();
}

Upvotes: 7

Views: 27677

Answers (2)

Greg Roberts
Greg Roberts

Reputation: 2562

I believe what you are looking for is a zoom behavior. Behaviors are objects that encapsulate some form of interactive behavior. I've seen several examples of "Zoom Behaviors" that you should be able to use for your project.

Upvotes: 3

Artem Kyba
Artem Kyba

Reputation: 885

Try to implement this sample:

    var canvas = new Canvas();
    var st = new ScaleTransform();
    var textBox = new TextBox {Text = "Test"};
    canvas.RenderTransform = st;
    canvas.Children.Add(textBox);
    canvas.MouseWheel += (sender, e) =>
    {
        if (e.Delta > 0)
        {
            st.ScaleX *= 2;
            st.ScaleY *= 2;
        }
        else
        {
            st.ScaleX /= 2;
            st.ScaleY /= 2;
        }
    };

Upvotes: 6

Related Questions