BSchlinker BSchlinker - 1 year ago 227
C# Question

Programmatically changing button icon in WPF

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" />

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

Answer Source

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

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

<Window x:Class="WpfApplication1.MainWindow"
    Title="MainWindow" Height="350" Width="525">
    <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"/>
    <Button Click="Button_Click" Name="MediaButton">
        <DynamicResource ResourceKey="Play"/>

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:


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

Edit: Shorter notation

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download