0

我用 ClickEvent 做了一个简单的自定义控件:

ImageButton.xaml:

<UserControl x:Name="ImgButton" x:Class="WpfApplication1.ImageButton"
         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" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
    <Grid></Grid>
</UserControl>

ImageButton.xaml.cs:

public partial class ImageButton : UserControl
{
    private bool mouse_down = false;
    private bool mouse_in = false;
    public event EventHandler Click;

    public ImageButton()
    {
        this.MouseEnter += new MouseEventHandler(ImageButton_MouseEnter);
        this.MouseLeave += new MouseEventHandler(ImageButton_MouseLeave);
        this.MouseLeftButtonDown += new MouseButtonEventHandler(ImageButton_MouseLeftButtonDown);
        this.MouseLeftButtonUp += new MouseButtonEventHandler(ImageButton_MouseLeftButtonUp);
        InitializeComponent();
    }

    void ImageButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if ((mouse_down)&&(mouse_in))
        {
            Click(this, null);
        }
        mouse_down = false;
    }

    void ImageButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        mouse_down = true;
    }

    void ImageButton_MouseLeave(object sender, MouseEventArgs e)
    {
        mouse_in = false;
    }

    void ImageButton_MouseEnter(object sender, MouseEventArgs e)
    {
        mouse_in = true;
    }
}

如果我正在处理 Click 事件,当我单击控件时它可以正常工作,否则我会崩溃。所以我该怎么做?

4

1 回答 1

0

您必须检查处理程序是否已添加到事件中,然后再启动它:

void ImageButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if ((mouse_down) && (mouse_in) && Click != null)
    {
        Click(this, null);
    }
    mouse_down = false;
}
于 2012-08-18T15:27:27.013 回答