有一个我不明白的有趣情况。
场景如下:
我创建了一个简单的 Silverlight 5 应用程序。 我在主页上放置了一个按钮控件并创建了一个 Click 事件处理程序。
XAML 如下所示.....
<UserControl x:Class="SilverlightApplication6.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="130,43,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</UserControl>
目前为止,一切都好。
在代码后面连接一个事件处理程序,这样....
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hi There!!!");
}
编译并运行应用。我"点击"按钮,得到一个漂亮的小消息框。再次,到目前为止,一切顺利。
将新方法(如下所示)添加到隐藏代码中,该方法名称与按钮单击事件处理程序相同,但签名不同。
private void button1_Click()
{
MessageBox.Show("This method causes a XamlParseException!");
}
编译并执行代码。打开应用程序并单击按钮,我得到以下异常:
System.Windows.Markup.XamlParseException was unhandled by user code
Message=Failed to assign to property 'System.Windows.Controls.Primitives.ButtonBase.Click'. [Line: 10 Position: 149]
LineNumber=10
LinePosition=149
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at SilverlightApplication6.MainPage.InitializeComponent()
at SilverlightApplication6.MainPage..ctor()
at SilverlightApplication6.App.Application_Startup(Object sender, StartupEventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(UInt32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName, UInt32 flags)
InnerException:
为什么会这样?
问题是void button1_Click()
不是Click
事件的有效处理程序。 Click
是一个RoutedEventHandler
,定义为:
public delegate void RoutedEventHandler(
Object sender,
RoutedEventArgs e
)
请注意,您也可以使用 void button1_Click(object anyName, EventArgs forTheParams)
,它只需要与委托足够紧密地匹配即可进行转换。
我有一个场景,我将按钮链接到这样的方法......
<Button Click="MethodName"..../>
我不知何故在不知道的情况下复制了该方法,结果我也得到了这个错误。无法分配给属性"系统.Windows.控件.基元.按钮库.单击希望这可以帮助某人节省一些时间。