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

巧了我就是萌 提交于 2019-12-06 19:30:04

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/41191758/uwp-xaml-how-to-display-a-button-with-icon-and-text-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!