简体   繁体   English

如何设置框架的背景图像?

[英]How to set background image for the frame?

I know in this article they set the background color using the steps followed. 我知道在本文中,他们使用以下步骤设置了背景色。 I was wondering if there was a way of using an image instead of a Color. 我想知道是否有一种使用图像而不是颜色的方法。 I tried the following but it didn't work: 我尝试了以下操作,但没有成功:

ImageBrush brush = new ImageBrush();
brush.ImageSource = 
new BitmapImage(new Uri("/MyApp;component/Images/Backgrounds/myimage.jpg"));
Rootframe.Background = brush;

Has anyone seen if this is possible? 有人看过这是否可能吗? Or is it restricted to Colors? 还是仅限于颜色?

I decided to have a go and got it working. 我决定去尝试一下。 The only catch is, it's a bit of a workaround since there seems to be some strange behaviour with the ImageOpened event. 唯一的问题是,这有点变通,因为ImageOpened事件似乎有些奇怪的行为。 Basically, the ImageOpened event of the Brush doesn't get called when you assign the background to the frame. 基本上,当您将背景分配给帧时,不会调用BrushImageOpened事件。 Strangely, it does get called when you assign it to an element. 奇怪的是,将其分配给元素时确实会调用它。 So I just created a hidden button and assigned the brush to that (to force the ImageOpened event to fire). 因此,我刚刚创建了一个隐藏按钮,并将画笔分配给该按钮(以强制触发ImageOpened事件)。 I then assigned it to the frame and it works for me. 然后,我将其分配给框架,它对我有用。 Seems like a bug, but the workaround below works for me. 似乎是一个错误,但是下面的解决方法对我有效。

ImageBrush brush = new ImageBrush();

brush.ImageSource = new BitmapImage(new Uri("/myImage.jpg", UriKind.Relative));
//hide the fake button and set the brush to be its background
button1.Visibility = System.Windows.Visibility.Collapsed;
button1.Background = brush;

//assign it to the frame (or using RootFrame in your case)
var frame = App.Current.RootVisual as PhoneApplicationFrame;
frame.Background = brush;

Using 使用

RootFrame.Background = App.Current.Resources["MainBackground"] as ImageBrush;

works for me. 为我工作。 You'll need the following in your resources dictionary in App.xaml 您将在App.xaml资源字典中需要以下内容

<ImageBrush x:Key="MainBackground" ImageSource="/resources/MainBackground.jpg" />

Set CreateOption to None or BackgroundCreation and wait while image is loaded: CreateOption设置为NoneBackgroundCreation并在加载图像时等待:

 BitmapImage image = new BitmapImage(new Uri("/MyApp;component/Images/Backgrounds/myimage.jpg"))
 {
      CreateOptions = System.Windows.Media.Imaging.BitmapCreateOptions.None
 };
 image.ImageOpened += (s, e) =>
 {
      brush.ImageSource = image;
      App.RootFrame.Background = brush;
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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