用户控件自定义事件崩溃

时间:2012-08-18 15:14:30

标签: c# wpf xaml user-controls

我用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事件,它是正确的,否则我会崩溃。那么,我该怎么办?

1 个答案:

答案 0 :(得分:0)

您必须先检查处理程序是否已添加到事件中,然后再进行操作:

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