Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP xaml: How to display a button with icon and text in it?

How can I display an image/icon AND text in a button?

<StackPanel Name="stackPanel" Orientation="Horizontal" Tapped="stackPanel_Tapped">
    <Button x:Name="button" FontFamily="Segoe MDL2 Assets" Content="&#xE779;" Width="50" Height="50" Background="Transparent" />
    <TextBlock Text="Grades" FontSize="18" VerticalAlignment="Center" />
</StackPanel>

I can add a taplistener to the stackpanel, but that won't make the stackpanel have visual effect like a real button.

I've also tried:

<Button FontFamily="Segoe MDL2 Assets" Width="50" Height="50" x:Name="button" Content="test">
   <Image x:Name="button" Source="Assets/test.png" />
</Button>

But I can't set the content twice. I want both text and an icon in a button so when a user clicks on it, it will have a visual effect like a button. Is this possible? Or does anyone else have another method to achieve this?

Thanks for reading.

like image 715
Denny Avatar asked Dec 16 '16 20:12

Denny


1 Answers

So since I couldn't find a direct duplicate (which I could swear this is the type of question that's been asked before) I guess I'll supply a legitimate answer.

At the heart of the button's template is a ContentPresenter which allows you to pass in any CLR object. The caveat though is that only one can be passed. HOWEVER, if that object is a panel capable of containing children then it will pass everything through as the content.

So in this instance if we did it this way:

<Button>
    <Image/>
    <TextBlock/>
</Button>

Then it will fail and complain about only one object allowed at a time.

Except when you provide a parent panel to hold those children, it respects it all as content and will provide the desired result as example:

<Button>
    <StackPanel>
        <Image/>
        <TextBlock/>
    </StackPanel>
</Button>

So since StackPanel is a CLR object that can host children, you're good to go. Hope this helps, cheers!

like image 182
Chris W. Avatar answered Nov 05 '22 04:11

Chris W.