我的目标是为每个页面设置一个背景图片。考虑一下这个结构。。。
/Images/AppBackground.jpg
/App.xaml
/MainPage.xaml
/Page2.xaml
我的第一次尝试是按照本网站其他地方的建议将其设置在根框架上…;)
应用程序.xaml.cs
ImageBrush brush = new ImageBrush
{
ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/AppBackground.jpg", UriKind.Relative)),
Opacity = 0.5d
};
this.RootFrame.Background = brush;
这将给我一个错误:A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
我尝试了使用和不使用起始/
,尝试了UriKind.Absolute
,并且没有UriType
参数,所有这些都会给我相同的错误。图像AppBackground.jpg
具有构建动作Content
。
下面的代码可以正常工作。
主页.xaml
<Grid x:Name="LayoutRoot">
<Grid.Background>
<ImageBrush ImageSource="/Images/AppBackground.jpg"></ImageBrush>
</Grid.Background>
...
但这不是我想要的,我不想为每一页设置它。。。
有人知道我搞砸了什么吗?)
Crap。错误的地方;我很早就到了。在构造函数中,它将简单地覆盖Background
设置。。。
如果我稍后执行它,它会很好地工作…:)
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
ImageBrush brush = new ImageBrush
{
ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/AppBackground.jpg", UriKind.Relative)),
Opacity = 0.5d
};
this.RootFrame.Background = brush;
}
在XAML中分别设置每个页面的背景有什么问题?如果背景应该是动态的,您可以实现一个状态标志,它将告诉应用程序它处于什么状态,从而知道要加载什么壁纸。
将其与绑定到转换器的后台相结合(将状态转换为ImageBrush
),您就有了解决方案。