简体   繁体   中英

WPF button with image doesn't appear

I'm using the following code I found on a question a few hours ago to make a button have an image:

            <Button Name="bPlay" Height="70" Width="70" Margin="359,480,349,11">
            <Button.Template>
                <ControlTemplate>
                    <Border HorizontalAlignment="Center" VerticalAlignment="Center">
                        <Image Source="pack://siteoforigin:,,,/Resources/play.bmp" Width="70" Height="70" />
                    </Border>
                </ControlTemplate>
            </Button.Template>
        </Button>

The problem is that for some reason it looks fine on Visual Studio, but when I run the program those buttons won't appear. I can't find the problem and I'm a little bit stuck. The image play.bmp is added to resources obviously, but still I don't know what the problem is, thanks!

"siteoforigin" in the URI indicates the file must be in the given path relative to the directory of the executing assembly. Your executable file is most likely in a bin/Debug folder. It's looking in the subdirectory of the executable, which probably doesn't exist ("bin/Debug/Resources/play.bmp").

If you want to link to the file that way then you have to tell Visual Studio to copy it to the output folder (from the Properties pane). Or copy it yourself.

Or better yet you should link to it as a resource and it will get embedded in the application. Set the file's build type to Resource in the properties pane, and link to it using the relative path in your project folder. In this case, literally write "Resources/play.bmp" in the XAML.

Try simplifying your code, perhaps just pull the image out and see if that displays.

<Button Name="bPlay" Height="70" Width="70" Margin="359,480,349,11">
    <Image Source="pack://siteoforigin:,,,/Resources/play.bmp" Width="70" Height="70" />
</Button>

should be valid as well

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