Issue displaying Canvas in Viewbox across multiple UserControls

Knox 26 Reputation points
2020-04-30T02:42:58.75+00:00

UPDATE: Apparently I have to set x:Shared to False on my Canvas elements in App.xaml.

I have some Canvas elements set as StaticResources in App.xaml that draw various icons. I also have a custom UserControl that simply displays a Button whose content is a Viewbox with a ContentPresenter where I then set a StaticResource.

For example...

    <Button>
        <Viewbox Margin="4">
            <ContentPresenter Content="{StaticResource ResourceKey=IconAdd}" />
        </Viewbox>
    </Button>

This works as expected if I have just 1 instance of the UserControl, but if I put multiple instances only the last one actually draws the Canvas icon. Any ideas why?

For example...

<StackPanel>

<controls:MyUserControlButton /> <!-- No icon -->
<controls:MyUserControlButton /> <!-- No icon -->
<controls:MyUserControlButton /> <!-- Shows icon -->

</StackPanel>

Thanks!

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,681 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Alex Li-MSFT 1,096 Reputation points
    2020-04-30T03:24:20.537+00:00

    Welcome to our Microsoft Q&A platform!

    I think you better use Grid instead of Stackpanel.

     <Grid>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <controls:MyUserControlButton Grid.Row="0"/>
            <controls:MyUserControlButton Grid.Row="1"/>
            <controls:MyUserControlButton Grid.Row="2"/>
        </Grid>
    

    Thanks.

    0 comments No comments

  2. Adrian Yankov 1 Reputation point
    2021-06-21T15:05:38.89+00:00

    I have the same issue. It looks like a bug. The icon is only shown in the last TreeViewItem for me. When I expand, it always moves it to the lower level.

    0 comments No comments