以编程方式更改 WPF 中的按钮图标 [英] Programmatically changing button icon in WPF

查看:34
本文介绍了以编程方式更改 WPF 中的按钮图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个按钮,上面有一个图标/图像.我已经在 XAML 中配置了按钮和图像:

I currently have a button, which has an icon/image on it. I have configured the button and image in XAML:

<Button Height="69" HorizontalAlignment="Left" Margin="-2,0,0,0" Name="toggleBroadcast" VerticalAlignment="Top" Width="64" Grid.Row="1" Opacity="0.5" Click="changeBroadcastState_Click">
        <Image Source="ImagesplayIcon.png" />
</Button>

我需要能够以编程方式将此按钮的图像从 playIcon 更改为 stopIcon.我该怎么做?

I need to be able to programmatically change this button's image from playIcon to stopIcon. How can I do this?

推荐答案

您可以通过事件处理程序更改按钮的内容来实现此目的.

You can accomplish this by changing the content of the button, through an event handler.

您可以在Window.Resources下将播放"图标和停止"图标设置为资源,如下所示:

You can set both the "Play" Icon and "Stop" Icon as a resource, under Window.Resources like so:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Image x:Key="Play" Source="/WpfApplication1;component/Play_Icon.png" Height="50" Width="50" />
    <Image x:Key="Stop" Source="/WpfApplication1;component/Stop_Icon.png" Height="50" Width="50"/>
</Window.Resources>
<Grid>
    <Button Click="Button_Click" Name="MediaButton">
        <DynamicResource ResourceKey="Play"/>
    </Button>
</Grid>

现在,当点击按钮时,您可以简单地将按钮的内容更改为不同的资源(停止图标).在按钮的事件处理程序中,您可以这样做:

Now, when the button is clicked, you can simply change the button's content to a different resource (the stop icon). In the button's event handler, you can do this:

C#

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (MediaButton.Content == FindResource("Play"))
    {
        MediaButton.Content = FindResource("Stop");
    }
    else
    {
        MediaButton.Content = FindResource("Play");
    }
}

更短的符号

MediaButton.Content = FindResource(MediaButton.Content == FindResource("Play") ? "Stop" : "Play");

希望这会有所帮助,如果您还有任何问题,请告诉我.

Hope this helps, let me know if you have any more questions.

这篇关于以编程方式更改 WPF 中的按钮图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆