ListBoxItem ContextMenu

今天想把listboxitem加上右键菜单,如下

<Style TargetType="{x:Type ListBoxItem}"
   BasedOn="{StaticResource ListBoxItemLDPStyle}">
  <Setter Property="ContextMenu">

    <Setter.Value>

      <ContextMenu>

          <MenuItem Header="Header" Click="MenuItem_Click"/>

      </ContextMenu>

    </Setter.Value>

  <Setter>
</Style>

总是编译不过System.Windows.Markup.XamlParseException 说什么Set connectionId threw an exception

google后发现http://stackoverflow.com/questions/5634022/why-setting-event-handlers-inside-a-setter-value-structure-gives-compilation-e

CodeNaked给了解释

his appears to be a bug in the generation of the XAML code-behind. In addition to the user code-behind for XAML files, there is a "compiler" generated version that defines InitializeComponent and class fields for named elements (i.e. x:Name).

Given a simple example:

<Window.Resources><StyleTargetType="Button"><Setter Property="ContextMenu"><Setter.Value><ContextMenu><MenuItem Header="Header" Click="MenuItem_Click"/></ContextMenu></Setter.Value></Setter></Style></Window.Resources><Button/>

If you run this, you will get the following exception:

System.Windows.Markup.XamlParseException occurred
  Message='Set connectionId threw an exception.'Line number '13'and line position '8'.Source=PresentationFrameworkLineNumber=13LinePosition=8StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e,IXamlLineInfo lineInfo,Uri baseUri)InnerException:System.InvalidCastExceptionMessage=Unable to cast object of type 'System.Windows.Controls.MenuItem' to type 'System.Windows.Controls.Button'.Source=Windows7ThemeStackTrace:
            at Windows7Theme.MainWindow.System.Windows.Markup.IComponentConnector.Connect(Int32 connectionId,Object target)in c:\Users\TJoe\Documents\Visual Studio10\Projects\Windows7Theme\Windows7Theme\MainWindow.xaml:line 13
            at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetConnectionId(Object root,Int32 connectionId,Object instance)InnerException:

The generated code-behind files can be found in the obj folder, so if we examine that we can see the following code:

voidSystem.Windows.Markup.IComponentConnector.Connect(int connectionId,object target){switch(connectionId){case1:#line13"..\..\..\MainWindow.xaml"((System.Windows.Controls.Button)(target)).AddHandler(System.Windows.Controls.MenuItem.ClickEvent,newSystem.Windows.RoutedEventHandler(this.MenuItem_Click));#linedefault#line hidden
    return;}this._contentLoaded =true;}

The issue here is the code generated is trying to cast the MenuItem to a Button. If we alter our sample like so:

<Window.Resources><ContextMenux:Key="ContextMenuKey"><MenuItemHeader="Header"Click="MenuItem_Click"/></ContextMenu><StyleTargetType="Button"><Setter Property="ContextMenu"
                Value="{StaticResource ContextMenuKey}"/></Style></Window.Resources><Button/>

Then the code generated is:

voidSystem.Windows.Markup.IComponentConnector.Connect(int connectionId,object target){switch(connectionId){case1:#line10"..\..\..\MainWindow.xaml"((System.Windows.Controls.MenuItem)(target)).Click+=newSystem.Windows.RoutedEventHandler(this.MenuItem_Click);#linedefault#line hidden
    return;}this._contentLoaded =true;}

Based on my tests, it appears the code generator assigns an ID to each control that it needs to "connect" or add handlers/backing fields for. In the case where the ContextMenu is included inline (i.e. the first example), it's event handlers are getting assigned to the root element inside the window and is not getting an ID of it's own.

If we changed Button to be contained in a Grid, then the exception above would indicate it failed to cast MenuItem to a Grid. Because now the Grid is the root element. This indicates it has nothing to do with the type the Style targets.

When the ContextMenu is included as a separate resource, the code generator seems to properly assign it an ID so it's handlers can be properly attached.

Ultimately, this is a bug in the XAML code generator.

posted on 2013-01-28 17:35  beastplus  阅读(1271)  评论(0编辑  收藏  举报

导航