用C#代码更改WPF窗口背景图像

bia*_*bit 27 c# wpf background-image

我有几个图像配置为应用程序资源.

当我的应用程序启动时,主窗口的背景是通过XAML设置的:

<Window.Background>
    <ImageBrush ImageSource="/myapp;component/Images/icon.png" />
</Window.Background>
Run Code Online (Sandbox Code Playgroud)

如果发生给定事件,我想将此背景更改为另一个资源("/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")));
Run Code Online (Sandbox Code Playgroud)

...但很自然地,我得到一个带有无效URI的例外.

有没有一种简单的方法来this.Background = ...使用包Uri或资源(即:) 更改WPF窗口的背景图像(via Myapp.Properties.Resources.icon)?

Dar*_*nda 39

那这个呢:

new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))
Run Code Online (Sandbox Code Playgroud)

或者,这个:

this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));
Run Code Online (Sandbox Code Playgroud)


Wii*_*axx 9

这里是XAML版本

<Window.Background>
    <ImageBrush>
        <ImageBrush.ImageSource>
            <BitmapImage UriSource="//your source .."/>
        </ImageBrush.ImageSource>
    </ImageBrush>
</Window.Background>
Run Code Online (Sandbox Code Playgroud)


Gur*_*ruC 6

问题是你在代码中使用它的方式.试试下面的代码吧

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在http://msdn.microsoft.com/en-us/library/aa970069.aspx中找到有关此内容的更多详细信息.