【问题标题】:WPF Interaction.Triggers MouseDown EventTrigger Not Working with Canvas ElementWPF Interaction.Triggers MouseDown EventTrigger 不适用于 Canvas 元素
【发布时间】:2016-07-24 20:44:39
【问题描述】:

我正在尝试创建一个允许我在窗口中绘制矩形的 MVVM WPF 应用程序。现在,我创建了一个覆盖整个屏幕的画布元素。在其他问题和指南之后,似乎对鼠标事件(例如MouseDownMouseUp 等)使用命令绑定的唯一方法是使用 System.Windows.Interactivity 程序集并为鼠标事件添加 EventTriggers。但是,这似乎不适用于 canvas 元素。单击,单击/按住,单击/拖动,右键单击,它们都不会触发我的命令的 Execute 方法。

画布元素支持哪些事件?为什么MouseDownPreviewMouseDown 不起作用?

窗口的 XAML:

<Window x:Class="RutheniumReader.SnippingWindow.SnippingShade"
    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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:snippingWindow="clr-namespace:MyApp.SnippingWindow"
    mc:Ignorable="d"
    Title="Snipping Window"
    WindowState="Maximized"
    Background="Black"
    >
    <Window.DataContext>
        <snippingWindow:SnippingWindowViewModel />
    </Window.DataContext>
    <Canvas x:Name="Canvas">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDown">
                <i:InvokeCommandAction Command="{Binding Path=MouseDownCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Canvas>
</Window>

出于测试目的,我尝试了以下事件,但没有成功:

  • 单击 - 如果我将其应用于画布内的 Button 元素,则可以使用
  • 鼠标按下
  • PreviewMouseDown - 使用 Button 元素
  • MouseLeftButtonDown
  • PreviewLeftMouseButtonDown

【问题讨论】:

    标签: c# wpf xaml mvvm eventtrigger


    【解决方案1】:

    鼠标事件不起作用,因为未设置画布的背景。 如果控件(在本例中为您的 Canvas)没有设置背景颜色,则背景颜色将默认为 null,这使得该控件不可命中测试。

    背景可以显式设置或通过样式设置,只要它的值不同于null(甚至是“透明”),它就应该拾取鼠标事件。

    【讨论】:

    • 是的,这行得通!不知何故,我认为这并不适用,因为我在窗口上设置了背景。
    • 这似乎是一个相当不直观的操作。不过答案很好
    • Transparent 对我不起作用(使用 Rectangle 元素),所以我将 Fill 设置为“#01000000”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多