我有几个图像配置为应用程序资源。
当我的应用程序启动时,主窗口的背景是通过 XAML 设置的:
<Window.Background>
<ImageBrush ImageSource="/myapp;component/Images/icon.png" />
</Window.Background>
如果给定的事件发生,我想将此背景更改为另一个资源(
"/myapp;component/Images/icon_gray.png"
)。
我试过使用两个常量:
private static readonly ImageBrush ENABLED_BACKGROUND =
new ImageBrush(new BitmapImage(new Uri("/myapp;component/Images/icon.png")));
private static readonly ImageBrush DISABLED_BACKGROUND =
new ImageBrush(new BitmapImage(new Uri("/myapp;component/Images/icon_gray.png")));
...但很自然地,我得到了无效 URI 的异常。
是否有一种简单的方法可以使用包 Uri 或资源(即:
this.Background = ...
)更改 WPF 窗口的背景图像(通过Myapp.Properties.Resources.icon
)?
这个呢:
new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))
或者,这个:
this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));
这里是 XAML 版本
<Window.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="//your source .."/>
</ImageBrush.ImageSource>
</ImageBrush>
</Window.Background>
问题是你在代码中使用它的方式。试试下面的代码
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource =
new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
this.Background = myBrush;
}
}
您可以在
中找到有关此的更多详细信息
http://msdn.microsoft.com/en-us/library/aa970069.aspx
我只是将一张图片放在"d drive-->Data-->IMG"。图片名称是
x.jpg
:
和 c# 代码类型
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));
(请在路径之间加上双斜线)
this.Background = myBrush;
终于拿到背景了..
Uri resourceUri = new Uri(@"/cCleaner;component/Images/cleanerblack.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
frame8.Background = brush;
我一直在尝试这里的所有答案,但没有成功。这是使用 ms-appx
执行此操作的最简单方法 ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(new Uri(@"ms-appx:///Assets/background.jpg"));
myBrush.ImageSource = image.Source;
TheGrid.Background = myBrush;
Assets文件夹在我项目的第一层,所以一定要改成方便的路径。
img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);