WinUI3xaml如何传递鼠标位置作为命令参数

xurqigkl  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(87)

我想将鼠标位置作为命令参数传递给我的命令,该命令在单击MenuFlyoutItem时执行。有人知道怎么做吗?我想有新的项目添加到'意见'集合出现在鼠标位置在画布上。我知道我可以在代码隐藏中完成它,但我不想这样做。

<controls1:CanvasView.ContextFlyout>
    <MenuFlyout>
        <MenuFlyoutItem Text="Add view" Command="{x:Bind ViewModel.AddViewCommand}" CommandParameter="{What to put here??}" />
    </MenuFlyout>
</controls1:CanvasView.ContextFlyout>
elcex8rz

elcex8rz1#

我想你需要跟踪鼠标的位置。
举例来说:

MainViewModel.cs

public partial class MainViewModel : ObservableObject
{
    [RelayCommand]
    private void AddView(Point point)
    {
    }
}

MainWindow.xaml.cs

[ObservableObject]
public sealed partial class MainWindow : Window
{
    [ObservableProperty]
    private Point _mousePosition;

    private void RootGrid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        PointerPoint point = e.GetCurrentPoint(this.RootGrid);
        MousePosition = point.Position;
    }

    public MainWindow()
    {
        this.InitializeComponent();
    }

    public ViewModel ViewModel { get; } = new();
}

**MainWindow.xaml

<Window
    x:Class="MousePositionExample.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:local="using:MousePositionExample"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid
        x:Name="RootGrid"
        Background="Transparent"
        PointerMoved="RootGrid_PointerMoved">
        <Canvas Background="Transparent">
            <Canvas.ContextFlyout>
                <MenuFlyout>
                    <MenuFlyoutItem
                        Command="{x:Bind ViewModel.AddViewCommand}"
                        CommandParameter="{x:Bind MousePosition, Mode=OneWay}"
                        Text="Add view" />
                </MenuFlyout>
            </Canvas.ContextFlyout>
        </Canvas>
    </Grid>

</Window>

注意

我使用CommunityToolkit.Mvvm NuGet包进行MVVM设计。

相关问题