Search code examples
xamlwin-universal-appresourcedictionary

UWP ResourceDictionary Style Error: The parameter is incorrect


I'm making a ResourceDictionary of common styles that are used throughout my application and one of them is:

<Style x:Key="ME_BASE_AppbarButtonSaveStyle"
       TargetType="AppBarButton">
    <Setter Property="Label"
            Value="Save" />
    <Setter Property="ToolTipService.ToolTip"
            Value="Save" />
    <Setter Property="Icon">
        <Setter.Value>
            <FontIcon FontFamily="Segoe MDL2 Assets"
                      Glyph="&#xE105;" />
        </Setter.Value>
    </Setter>
</Style>

It's all ok if I apply the style only one AppbarButton on the Page, but if I want to have two buttons with the same style, I get the following error:

The parameter is incorrect

It's of ok (no error) if I remove the icon property out of the style... But that's kind of missing the point...

Anyone experienced something similar? Perhaps...

Thank you for all the help.


Solution

  • Error HRESULT E_Fail has been returned from a call to a COM component.

    This error will occurred when you use this style for the second AppBarButton. This error usually happens when a reference to a style or an event handler that does not exist or is not with the context of the XAML, you can see the exception information of your problem: enter image description here

    If you read this document: XAML resources must be shareable, you will find:

    Custom types used as resources can't have the UIElement class in their inheritance, because a UIElement can never be shareable (it's always intended to represent exactly one UI element that exists at one position in the object graph of your runtime app).

    Whether a Icon property of AppBarButton or a FontIcon derives from UIElement, so I guess this is the reason why can't this property be styled in the resource dictionary.

    Besides, I will consider if this is a right direction to define the Icon property for each AppBarButton in the style, normally I'd like give each button a different icon as content.

    But if you insist to do this, I can provide you a workaround method by defining the Content of the AppBarButton, this is the construction of your AppBarButton: enter image description here

    You use a FontIcon as the content of the AppBarButton, so we can modify your style like this:

    <Style x:Key="ME_BASE_AppbarButtonSaveStyle" TargetType="AppBarButton">
        <Setter Property="Label" Value="Save" />
        <Setter Property="ToolTipService.ToolTip" Value="Save" />
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <FontIcon FontFamily="Segoe MDL2 Assets"
                  Glyph="&#xE105;" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>