Search code examples
wpfxamlstylesexpression-blend

Setting Icon property value of MenuItem using style in XAML as Shapes.Path


I am using Silverlight 4 and Expression Blend 4.

I am styling a MenuItem with a path as Icon.

<Style x:Key="1234" TargetType="Controls:MenuItem">
        <Setter Property="Header" Value="Cancel" />
        <Setter Property="Icon">
            <Setter.Value>
                <Path Fill="#FF2B2B2B"
                      Width="14.3775"
                      Height="14"
                      Canvas.Left="0.311264"
                      Canvas.Top="0.500005"
                      Stretch="Fill"
                      Data="F1 M 111.2,-85.6L 124.2,-85.6L 124.2,-72.6L 111.2,-72.6L 111.2,-85.6 Z M 117.791,-82.3439L 117.791,-80.4506L 112.685,-80.4506L 112.685,-77.8084L 117.791,-77.8084L 117.791,-75.8748L 121.025,-79.1094L 117.791,-82.3439 Z M 121.657,-84.0222L 121.657,-74.0222L 122.657,-74.0222L 122.657,-84.0222L 121.657,-84.0222 Z " />
            </Setter.Value>
        </Setter>
    </Style>

But this gives an exception expression blend when I try to open this.

Exception Message: Error HRESULT E_FAIL has been returned from a call to a COM component at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cdData)

This also gives exception at runtime when I add this style to a ContextMenu's item.


Solution

  • Put the styling in control template:

    <ControlTemplate x:Key="CancelIcon">
          <Canvas>
            <Path Fill="#FF2B2B2B"
                              Width="14.3775"
                              Height="14"
                              Canvas.Left="0.311264"
                              Canvas.Top="0.500005"
                              Stretch="Fill"
                              Data="F1 M 111.2,-85.6L 124.2,-85.6L 124.2,-72.6L 111.2,-72.6L 111.2,-85.6 Z M 117.791,-82.3439L 117.791,-80.4506L 112.685,-80.4506L 112.685,-77.8084L 117.791,-77.8084L 117.791,-75.8748L 121.025,-79.1094L 117.791,-82.3439 Z M 121.657,-84.0222L 121.657,-74.0222L 122.657,-74.0222L 122.657,-84.0222L 121.657,-84.0222 Z " />
          </Canvas>
        </ControlTemplate>
    

    Then for menu try the following

    <MenuItem Header="Cancel" >
      <MenuItem.Icon>
        <ContentControl Template="{StaticResource CancelIcon}" />
      </MenuItem.Icon>
    </MenuItem>
    

    Hope this will work out :-)