Search code examples
c#wpfcode-behind

Check which image is currently shown? WPF


I got a label which triggers this function everytime I press enter

private void WordInput_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            WordInput.Text = String.Empty;
            Smiley.Source = new BitmapImage(new Uri(@"FailSmile2.png", UriKind.Relative));
        }
    }

Which changes a picture to the one above(FailSmile2.png) But now, I want to check, if it's FailSmile2 that is being shown, then I want to change to another picture instead, with the same function. Should I use a cuople of IF to check the source? In that case, how?

Thanks!


Solution

  • Could just store it as a private field on your class:

    private string CurrentImagePath;
    
    private void WordInput_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            WordInput.Text = String.Empty;
    
            if (CurrentImagePath == null)
                CurrentImagePath = @"FailSmile2.png";
            else if (CurrentImagePath == @"FailSmile2.png")
                CurrentImagePath = @"SomeOtherImage.png";
    
            Smiley.Source = new BitmapImage(new Uri(CurrentImagePath, UriKind.Relative));
        }
    }
    

    Not sure about what exactly you want to do. If you plan on cycling through multiple images, it may be better to store those in a List<Uri> and cycle through them one at a time. Essentially, somehow you'll want to store the current state of your control (likely as a private field) and based on that make changes or possibly wire different events.