WPF关于为启动屏幕显示图像的问题
本文关键字:图像 问题 屏幕显示 启动 WPF | 更新日期: 2023-09-27 17:58:57
我的项目中有一个图像。
在解决方案资源管理器中,我创建了一个名为"Resources"的文件夹,并在该文件夹中添加了一个图像。
我想将图像设置为该文件夹中的文件。这是我的C#代码
BitmapImage splashScreenImageSource = new BitmapImage();
splashScreenImageSource.BeginInit();
splashScreenImageSource.UriSource = new Uri("world_splash.jpg", UriKind.Relative);
splashScreenImageSource.EndInit();
splashScreenImage.Source = splashScreenImageSource;
当我跑步时,什么也没发生。
这是我的XAML代码
<Window x:Class="Bail.SplashScreen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/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>
谢谢你的帮助。如果你需要看,这里是App.xaml
<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>
我认为您必须在图像路径中指定子目录。你说它在"资源"中。所以尝试使用:
splashScreenImageSource.UriSource = new Uri("Resources/world_splash.jpg", UriKind.Relative);
编辑:您必须将文件类型设置为resource才能工作。如果你想把它作为文件系统中的一个文件(而不是嵌入到程序集中),你必须使用一个pack-uri,比如:
splashScreenImageSource.UriSource = new Uri("pack://siteoforigin:,,,/Resources/world_splash.jpg", UriKind.Relative);
在这种情况下,请确保设置了文件的"复制到输出目录"选项。
还可以考虑直接从XAML进行初始化。它看起来更干净,需要更少的代码:
<Image x:Name="splashScreenImage" Stretch="Fill" Grid.Row="0" Source="Resources/world_splash.jpg" />