更改C#代码中的WPF窗口背景图像
我有几个映像配置为应用程序资源 当我的应用程序启动时,通过XAML设置主窗口的背景:更改C#代码中的WPF窗口背景图像,c#,wpf,background-image,C#,Wpf,Background Image,我有几个映像配置为应用程序资源 当我的应用程序启动时,通过XAML设置主窗口的背景: <Window.Background> <ImageBrush ImageSource="/myapp;component/Images/icon.png" /> </Window.Background> 。。。但很自然,我会得到一个URI无效的异常 是否有一种简单的方法可以使用包Uri或资源(即:Myapp.Properties.Resources.icon)更改
<Window.Background>
<ImageBrush ImageSource="/myapp;component/Images/icon.png" />
</Window.Background>
。。。但很自然,我会得到一个URI无效的异常
是否有一种简单的方法可以使用包Uri或资源(即:Myapp.Properties.Resources.icon
)更改WPF窗口的背景图像(通过this.background=…
) 这个呢:
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")));
问题在于您在代码中使用它的方式。请尝试下面的代码
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;
}
}
您可以在这里是XAML版本
<Window.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="//your source .."/>
</ImageBrush.ImageSource>
</ImageBrush>
</Window.Background>
我只在的“d驱动器-->数据-->IMG”中放置了一个图像。图像名称为
x.jpg
:
和在c#代码类型上
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));
(请在路径之间加上双斜杠)
我终于了解了背景 我一直在尝试这里的所有答案,但都没有成功。下面是使用ms appx执行此操作的最简单方法
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;
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;
“资产”文件夹位于我的项目的第一级,因此请确保方便地更改路径。img.UriSource=new Uri(“pack://application:,,,/images/“+文件名,UriKind.Absolute) 使用第二个,因为我定义了一个静态常量。谢谢
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;
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;