在我的WPF应用程序中,我为上下文菜单项添加了click事件处理程序(ListBoxItem的上下文菜单)。
当我尝试以下方法时:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Remove" Click="RemoveSelectedSchedule"/>
</ContextMenu>
</Setter.Value>
</Setter>
<EventSetter Event="MouseDoubleClick" Handler="ScheduleList_MouseDoubleClick"/>
</Style>
</ListBox.ItemContainerStyle>
并尝试构建,构建失败并显示以下错误消息:
1&gt; C:\ Users \ Pawel \ Source \ Repos \ academiccalendar \ AcademicCalendar.Desktop \ _ obj \ Debug \ MainWindow.g.cs(113,14,113,15):错误CS1513:}预期 1&gt; C:\ Users \ Pawel \ Source \ Repos \ academiccalendar \ AcademicCalendar.Desktop \ _ obj \ Debug \ MainWindow.g.cs(123,19,123,20):错误CS1514:{预期 1&gt; C:\ Users \ Pawel \ Source \ Repos \ academiccalendar \ AcademicCalendar.Desktop \ _ obj \ Debug \ MainWindow.g.cs(125,9,125,10):错误CS1525:无效的表达式术语&#39;}&#39 ; 1&gt; C:\ Users \ Pawel \ Source \ Repos \ academiccalendar \ AcademicCalendar.Desktop \ _ obj \ Debug \ MainWindow.g.cs(125,10,125,11):错误CS1002 :;预期
但是,如果为Context MenuItem删除了设置Click事件处理程序,则代码将编译并正常运行。
EDIt事件处理程序当前为空。
void RemoveSelectedSchedule(object sender, RoutedEventArgs e)
{
}
答案 0 :(得分:2)
这很奇怪......
经过一段时间的游戏,我得到了编译
删除代码
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Remove" Click="RemoveSelectedSchedule"/>
</ContextMenu>
</Setter.Value>
</Setter>
编译 - 失败
添加第二个EventSetter
编译失败
添加代码
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Remove" Click="RemoveSelectedSchedule"/>
</ContextMenu>
</Setter.Value>
</Setter>
WPF编译器有问题......
编辑1更好的答案......
如果将ContextMenu移动到资源部分
<ContextMenu x:Key="ListBoxItemContextMenu">
<MenuItem Header="View" Name="MenuItemView" Click="ContextClicked"/>
</ContextMenu>
然后在Setter中访问它似乎工作
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="ContextMenu" Value="{StaticResource ListBoxItemContextMenu}">
</Setter>
<EventSetter Event="MouseDown" Handler="EventSetter_OnHandler1"></EventSetter>
<EventSetter Event="MouseDoubleClick" Handler="EventSetter_OnHandler2"></EventSetter>
</Style>