动态事件处理 - 不发射



我在动态处理MouseUp事件时遇到问题。带有问题的测试代码:

WPF:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="Button1" Content="Button1" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
        <Button x:Name="Button2" Content="Button2" HorizontalAlignment="Left" Margin="10,37,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

c#背后:

using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Button2.MouseLeftButtonUp += something;
        }
        private void something(object sender, MouseEventArgs e)
        {
            MessageBox.Show("TEST");
            Button2.MouseLeftButtonUp -= something;
        }
    }
}

现在,我希望带有文本"测试"的MessageBox仅在我单击Button2之后单击CC_3后才显示。它没有显示。相同的代码可以与Click事件一起使用,但是我需要MouseUp来获取鼠标位置。我已经确认第一个功能会发射,但是第二个功能并非我尝试什么。帮助?

请参阅buttonbase.click中的备注部分:

按钮标记了Mouseleftbuttondown事件 OnMouseleftButtondown方法并提出了点击事件。因此, Onmouseleftbuttondown事件将永远不会发生 从按钮键继承。相反,将事件处理程序附加到 PreviewMouseleftButtondown事件,或致电Addhandler(RoutedEvent, 委托,布尔值)带有andledEventStoo设置为true。

由于MouseLeftButtonDown是内部处理的,您也将没有 MouseLeftButtonUp事件。但是,您可以改用PreviewMouseleftButtonUp事件。

最新更新