【问题标题】:Mouse Events on WPF Page - On sub controls only?WPF 页面上的鼠标事件 - 仅在子控件上?
【发布时间】:2015-05-29 11:48:57
【问题描述】:

我正在开发一个 C# WPF 项目。 MainWindows 只包含一个Frame Control,用于导航到不同的页面。

在一个页面上,我使用Button 来显示PopUp。现在我想在鼠标离开它并移动到Page上方时隐藏这个弹出窗口。

<Page x:Class="Name.SpaceMainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  Title="MainPage"
  MouseMove="Page_MouseMove">

    <StackPanel>
        <Label Content="Some Label"/>
        <Label Content="Other Label"/>
        <Button Name="PopupButton" Content="Popup" Click="MenuButtonClick" /> 
        <Label Content="Third Label"/>

        <Popup Name="ExtrasPopup" PlacementTarget="{Binding ElementName=PopupButton}" Placement="Top" PopupAnimation="Scroll">
            <StackPanel Background="LightGray">
                ...
            </StackPanel>
        </Popup>
    </Grid>
</Page>


public partial class MainPage : Page {
    ...

    private void MenuButtonClick(object sender, RoutedEventArgs e) {
        ExtrasPopup.IsOpen = true;
    }

    private void Page_MouseMove(object sender, MouseEventArgs e) {
        System.Diagnostics.Debug.WriteLine("Move: " + e.MouseDevice.GetPosition(this));
    }
}

问题: Page_MouseMove 仅在鼠标移到子控件(标签或按钮)上方时执行。如果鼠标移动到页面的空白区域上方,则不会触发该事件。

对于任何其他鼠标事件(例如 MouseDown、MouseEnter、MouseLeave 等)也是如此……这是一种非常奇怪的行为。这是故意的还是我犯了什么错误?

【问题讨论】:

  • 试试&lt;Page Background="Transparent"。鼠标事件仅在 Background not null 上触发。
  • @LPL 非常感谢!这就是解决方案!

标签: c# wpf mouseevent


【解决方案1】:

最好在 Button 或您要使用的任何控件上注册 MouseLeave 事件。

<Button Name="PopupButton" Content="Popup" Click="MenuButtonClick" MouseLeave="Menu_MouseLeave" />

并且在后面的代码中,只需在鼠标离开按钮时隐藏弹出窗口:

private void Menu_MouseLeave(object sender, MouseEventArgs e)
{
   ExtrasPopup.IsOpen = false;
}

【讨论】:

  • 弹出窗口显示在按钮单击上,它还包含一些控件(复选框、按钮等)。因此,鼠标必须离开按钮才能到达弹出窗口内的控件...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多