自定义按钮异常



我是WPF和C#开发的新手。我正在尝试基于标准WPF按钮创建自己的按钮类。

public class _BaseButton : Button
{
public _BaseButton() : base()
{
}
}

然后我尝试将它放在XAML中的Window中。

<Window x:Class="Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sample"
Title="MainWindow" Height="350" Width="525">
<Grid >
<local:_BaseButton Height="30" Width="100" Content="I am crashing" VerticalAlignment="Center" PreviewMouseLeftButtonDown="simpleButtonDetailCancelButton_PreviewMouseLeftButtonDown"/>
</Grid>
</Window>

正如您所看到的,在XAML代码中,我定义了PreviewMouseLeftButtonDown事件的处理程序。它是在窗口代码后面实现的。

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void simpleButtonDetailCancelButton_PreviewMouseLeftButtonDown(object sender, RoutedEventArgs e)
{
}
}

这样一个简单应用程序的构建完成时不会出现错误。当我运行应用程序时,它崩溃了,有以下两个例外:

System.Windows.Markup.XamlParseException:无法从文本simpleButtonDetailCancelButton_PreviewMouseLeftButtonDown创建预览鼠标左键。线路编号7和线路位置10。

ArgumentException:无法绑定到目标方法,因为其签名或安全透明性与委托类型的签名或安全透明度不兼容。

你能解释一下我做错了什么吗?PreviewMouseLeftButtonDown事件处理程序的定义有问题,或者基类中缺少它,但我不知道该怎么做才能修复它

将事件处理程序的第二个参数的类型更改为MouseButtonEventArgs:

private void simpleButtonDetailCancelButton_PreviewMouseLeftButtonDown(object sender, 
MouseButtonEventArgs e)
{ 
}

签名不正确。如果我让visualstudio定义它的签名:

private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}

因此,您的事件参数应该是MouseButtonEventargs;not RoutedEventArgs

最新更新