Search code examples
wpfwpf-controlsstackpanel

How to set the position of StackPanel same as position of mouse pointer after click


  • I have Stack Panel in WPF application of height = 200, width = 200.
  • Its invisible by default.
  • I want to make stack panel visible on left click and want to set its position same as mouse pointer.

Can anybody tell me how to do that. Thank you :)


Solution

  • You could make it visible by handling the MouseLeftButtonDown event and set the Visibility of the StackPanel to Visible. For you to be able to explicitly position it using coordinates you could put it in a Canvas and handle the MouseLeftButtonDown event for the Canvas. Please refer to the following sample code.

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApplication1"
            mc:Ignorable="d"
            Title="MainWindow" Height="700" Width="700">
        <Canvas x:Name="canvas" Background="Transparent" MouseLeftButtonDown="Canvas_MouseLeftButtonDown">
            <StackPanel x:Name="sp" Background="Yellow" Width="200" Height="200" Visibility="Hidden" />
        </Canvas>
    </Window>
    
    
    private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Point point = e.GetPosition(canvas);
        Canvas.SetLeft(sp, point.X - sp.Width / 2);
        Canvas.SetTop(sp, point.Y - sp.Height / 2);
        sp.Visibility = Visibility.Visible;
    }