Programmatically changing button icon in WPF

前端 未结 4 1229
忘掉有多难
忘掉有多难 2020-12-01 12:50

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

4条回答
  •  萌比男神i
    2020-12-01 13:12

    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:

    
    
        
        
    
    
        
    
    

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

    Edit: Shorter notation

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

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

提交回复
热议问题