[英]Crash on user control custom event
我使用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事件,则单击控件时它可以正常工作,否则会崩溃。 所以我该怎么做?
您必须先检查是否已将处理程序添加到事件中,然后再进行提升:
void ImageButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if ((mouse_down) && (mouse_in) && Click != null)
{
Click(this, null);
}
mouse_down = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.