简体   繁体   中英

C#: How do I view an image when a user clicks on a button?

I've seen many different versions of the same answer, none of which have solved my problem. I'm using a WPF and I want an image to view when the user clicks on a button "hint". Here's the code so far:

    void Hint_Click(object sender, RoutedEventArgs e)
    {
        Label.Content = "Yes";
        BitmapImage RealTrump = new BitmapImage(new Uri("RealTrump", UriKind.Relative));
    }

It's a jpeg image and is saved within the project file so the directory is just "RealTrump". When I run through compiler and click the button it just views the label and not the image.

Here's the XAML code, I really don't know what to do with it as I'm still pretty new to c# and programming in general:

<Image x:Name="RealTrump" HorizontalAlignment="Left" Height="100" Margin="381,44,0,0" VerticalAlignment="Top" Width="97"/>

I'm on Visual Studio 2013 if that helps.

While you have given your label the name RealTrump you've created a local variable of the same name in the click event handler.

If you simply remove the type declaration and set the image source like this:

void Hint_Click(object sender, RoutedEventArgs e)
{
    Label.Content = "Yes";
    RealTrump.Source = new BitmapImage(new Uri("pack://application:,,,/Images/RealTrump.jpg", UriKind.Relative));
}

The image should be displayed. (You may have to adjust the path slightly depending on exactly where it is relative to your source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM