单击后如何将StackPanel的位置设置为与鼠标指针的位置相同
How to set the position of StackPanel same as position of mouse pointer after click
- 我在 WPF 应用程序中有堆栈面板,高度 = 200,宽度 = 200。
- 默认不可见。
- 我想让堆栈面板在左键单击时可见,并想设置它
位置与鼠标指针相同。
谁能告诉我该怎么做。谢谢:)
您可以通过处理 MouseLeftButtonDown 事件并将 StackPanel 的 Visibility 设置为 Visible 使其可见。为了能够使用坐标显式定位它,您可以将它放在 Canvas 中并处理 Canvas 的 MouseLeftButtonDown 事件。请参考下面的示例代码。
<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;
}
- 我在 WPF 应用程序中有堆栈面板,高度 = 200,宽度 = 200。
- 默认不可见。
- 我想让堆栈面板在左键单击时可见,并想设置它 位置与鼠标指针相同。
谁能告诉我该怎么做。谢谢:)
您可以通过处理 MouseLeftButtonDown 事件并将 StackPanel 的 Visibility 设置为 Visible 使其可见。为了能够使用坐标显式定位它,您可以将它放在 Canvas 中并处理 Canvas 的 MouseLeftButtonDown 事件。请参考下面的示例代码。
<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;
}