如何在 C# 代码中更改 Fontawesome.wpf 图标

How to change Fontawesome.wpf Icon in c# code

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

And finally in your C# code behind:

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;
     }
}

如前所述,单击按钮时不会显示图标,只会显示文本 "Stop",再次按下时 "Play"。

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 };