编程改变WPF按钮图标 [英] Programmatically changing button icon in WPF

查看:879
本文介绍了编程改变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="Images\playIcon.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");
        }
    }

编辑:更短的符号

Shorter notation

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天全站免登陆