开发者

WPF Question about displaying the image for Splash Screen

开发者 https://www.devze.com 2023-03-11 22:19 出处:网络
I have an image in my project. In Solution Explorer, I\'ve created a folder called \"Resources\" and I\'ve added a single image in to that folder.

I have an image in my project.

In Solution Explorer, I've created a folder called "Resources" and I've added a single image in to that folder.

I want to set the image to the file in that folder. Here's my C# code

BitmapImage splashScreenImageSource = new BitmapImage();
splashScreenImageSource.BeginInit();
splashScreenImageSource.UriSource = new Uri("world_splash.jpg", UriKind.Relative);
splashScreenImageSource.EndInit();            
splashScreenImage.Source = splashScreenImageSource;

When I run, nothing happens.

Here's my XAML code

<Window x:Class="Bail.SplashScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xa开发者_如何学JAVAml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="256" Width="456" Background="#00005555" AllowsTransparency="True" WindowStyle="None" WindowStartupLocation="CenterScreen" >
    <Grid Width="Auto">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>        
        <Image x:Name="splashScreenImage" Stretch="Fill" Grid.Row="0" />
    </Grid>
</Window>

Thank you for all your help. Here is App.xaml if you needed to see

<Application x:Class="Bail.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="SplashScreen.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>


I think you have to specify the subdirectory in the image path. You said it's in "Resources". So try using:

splashScreenImageSource.UriSource = new Uri("Resources/world_splash.jpg", UriKind.Relative);

Edit: You have to set the file type to resource for this to work. If you want to have it as a file in the file system (instead of embedded in your assembly) you have to use a pack uri, like:

splashScreenImageSource.UriSource = new Uri("pack://siteoforigin:,,,/Resources/world_splash.jpg", UriKind.Relative);

In this case make sure the "Copy to output directory" option of the file is set.

Also consider doing the initalization directly from XAML. It looks cleaner and requires less code:

<Image x:Name="splashScreenImage" Stretch="Fill" Grid.Row="0" Source="Resources/world_splash.jpg" />
0

精彩评论

暂无评论...
验证码 换一张
取 消