简体   繁体   中英

Using C#, can you drag a canvas in WPF?

Can you drag a canvas in WPF? How do you set the position of the canvas? Here is what I got so far:

/// xaml

<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="350" Width="525"
        WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True"
        Background="Transparent" Loaded="MainWindow_Loaded">


    <Canvas Name="ParentCanvas" Background="#FF6E798D">
    </Canvas>
</Window>

/// code behind

public partial class MainWindow : Window
{
    private Boolean isMouseCapture;

    public MainWindow()
    {
        InitializeComponent();
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {            
        this.ParentCanvas.MouseLeftButtonDown += new MouseButtonEventHandler(_MouseLeftButtonDown);
        this.ParentCanvas.MouseLeftButtonUp += new MouseButtonEventHandler(_MouseLeftButtonUp);
        this.ParentCanvas.MouseMove += new MouseEventHandler(_MouseMove);
    }

    void _MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        this.ParentCanvas.ReleaseMouseCapture();
        isMouseCapture = false;
    }

    void _MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.ParentCanvas.CaptureMouse();
        isMouseCapture = true;
    }

    void _MouseMove(object sender, MouseEventArgs e)
    {
        if (isMouseCapture)
        {
            this.ParentCanvas.X= e.GetPosition(this).X;
            this.ParentCanvas.Y = e.GetPosition(this).Y;
        }
    }
}

'X' is not a property of Canvas (ie"this.ParentCanvas.X"). What do I use to set the position?

To set the position of an element in pixels, the element must be contained in a Canvas panel.

You can then call Canvas.SetTop and Canvas.SetLeft .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM