How to switch images in a C# WPF application?

后端 未结 2 1839
抹茶落季
抹茶落季 2021-01-24 10:21

I am trying to make an application that switches between an image of the heads sign of a coin and the tails side of a coin. However, every time I press either the \"heads\" butt

2条回答
  •  借酒劲吻你
    2021-01-24 11:09

    You can't use the sender argument, because that's the Button, not the Image control.

    Use the coinImage member instead:

    private void headsButton_Click(object sender, RoutedEventArgs e)
    {
        coinImage.Source = new BitmapImage(new Uri(@"C:\Users\Raymond Karrenbauer\Documents\Visual Studio 2015\Projects\HeadsOrTails\heads.jpg"));
    }
    
    private void tailsButton_Click(object sender, RoutedEventArgs e)
    {
        coinImage.Source = new BitmapImage(new Uri(@"C:\Users\Raymond Karrenbauer\Documents\Visual Studio 2015\Projects\HeadsOrTails\tails.jpg"));
    }
    

    Besides that, you should add both image files to your Visual Studio project, set their Build Action to Resource and access them by a Resource File Pack URI. This way you wouldn't have to deal with absolute file paths:

    private void headsButton_Click(object sender, RoutedEventArgs e)
    {
        coinImage.Source = new BitmapImage(new Uri("pack://application:,,,/heads.jpg"));
    }
    
    private void tailsButton_Click(object sender, RoutedEventArgs e)
    {
        coinImage.Source = new BitmapImage(new Uri("pack://application:,,,/tails.jpg"));
    }
    

    You may then also add the BitmapImages as XAML Resources:

    
        
            
            
        
        ...
    
    

    And use them like this:

    private void headsButton_Click(object sender, RoutedEventArgs e)
    {
        coinImage.Source = (ImageSource)Resources["heads"];
    }
    
    private void tailsButton_Click(object sender, RoutedEventArgs e)
    {
        coinImage.Source = (ImageSource)Resources["tails"];
    }
    

提交回复
热议问题