首页 > 解决方案 > 如何在 C# 代码中更改 Fontawesome.wpf 图标

问题描述

我对 wpf 编程相当陌生,所以这可能很基本,但我不知道如何动态更改按钮的 FontAwesome 图标(在 c# 代码中)。我在这里使用本文中描述的 nuget 包。然而最后一部分:

最后在你的 C# 代码后面:

using FontAwesome.WPF; // on the top of the code
btnButton.Content = FontAwesomeIcon.LongArrowRight;

对我不起作用,因为它仅在单击按钮后显示文本“LongArrowRight”。

这是我的代码:

<Window
...
xmlns:fa="http://schemas.fontawesome.io/icons/">

<Grid>
    <Button x:Name="btnPlay" Click="btnPlay_Click">
        <Button.Content>
            <fa:ImageAwesome Icon="Play"/>
        </Button.Content>
    </Button>
</Grid>

</Window>
using FontAwesome.WPF; // at the top

private bool running = false;
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
     if (running) 
     {
         running = false;
         btnPlay.Content = FontAwesomeIcon.Play;
     }
     else
     {
          running = true;
          btnPlay.Content = FontAwesomeIcon.Stop;
     }
}

如前所述,单击按钮时它不显示图标,而仅显示文本“停止”,再次按下“播放”时。

标签: c#wpffont-awesome

解决方案


FontAwesomeIcon是枚举。当您将枚举值分配给 Button.Content 时,它将显示为文本。

您需要将ImageAwesome元素分配给内容:

btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.LongArrowRight };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Play };
btnPlay.Content = new ImageAwesome { Icon = FontAwesomeIcon.Stop };

推荐阅读