Search code examples
c#.netxamluwpwin-universal-app

How to make PathIcon stretch in UWP


I want to use PathIcon just as same size with the text, like NavigationItem. I tried to use <Image> to implement it like this.

image

but I want to use icon because it can auto change color in dark or white mode.

<StackPanel Orientation="Horizontal" >
    <Rectangle Width="20" Fill="BlanchedAlmond"/>
    <PathIcon Data="{StaticResource PowerPlantIcon}"/>
    <Rectangle Width="20" Fill="BlanchedAlmond"/>
    <PathIcon Data="{StaticResource PowerPlantIcon}" Height="20"/>
    <TextBlock Text="This is a Text" FontSize="20" VerticalAlignment="Center"/>
</StackPanel>

And I get this:

image

Here is my custom PathIcon defined in App.xmal

<x:String x:Key="PowerPlantIcon">
   M43,50H36.12V46.24h5.27l4.85-4.85V8.55L41.38,3.76H36.12V0H43l7,7V43ZM13.87,50H7L0,43V7L7,0h6.88V3.76H8.55L3.76,8.55V41.38l4.79,4.79h5.33Zm4.7-7.06L32.46,23.59l-7-.58L31.35,8.7H20.29L17.56,25.53l4.44.55Z
</x:String>

I find the icon size has been auto set to 50x50 and cannot be changed through setting width or height.

After search everything I can find, did not find the solution to make PathIcon stretch.


Solution

  • You could adjust the size of a PathIcon by putting the PathIcon into a ViewBox. You could bind the Width property and Height property of the ViewBox control to the TextBlock control to implement the stretch effect.

    Please check the following code as a reference:

    <StackPanel Orientation="Horizontal" >
        <Rectangle Width="20" Fill="BlanchedAlmond"/>
        <PathIcon Data="{StaticResource PowerPlantIcon}"/>
        <Rectangle Width="20" Fill="BlanchedAlmond"/>
        
        <Viewbox Height="{Binding Path=ActualHeight,ElementName=textBlock}" Width="{Binding Path=ActualHeight,ElementName=textBlock}">
            <PathIcon Data="{StaticResource PowerPlantIcon}"/>
        </Viewbox>
        <TextBlock x:Name="textBlock" Text="This is a Text" FontSize="20" VerticalAlignment="Center"/>
    </StackPanel>