Change WPF window background image in C# code

后端 未结 7 1650
梦毁少年i
梦毁少年i 2020-12-09 08:11

I have a couple of Images configured as application resources.

When my application starts, the background of the main window is set via XAML:



        
相关标签:
7条回答
  • 2020-12-09 08:38

    The problem is the way you are using it in code. Just try the below code

    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;
        }
    }
    

    You can find more details regarding this in
    http://msdn.microsoft.com/en-us/library/aa970069.aspx

    0 讨论(0)
  • 2020-12-09 08:42

    img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

    0 讨论(0)
  • 2020-12-09 08:43

    i just place one image in " d drive-->Data-->IMG". The image name is x.jpg:

    And on c# code type

    ImageBrush myBrush = new ImageBrush();
    
    myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));
    

    (please put double slash in between path)

    this.Background = myBrush;
    

    finally i got the background.. enter image description here

    0 讨论(0)
  • 2020-12-09 08:47

    Here the XAML Version

    <Window.Background>
        <ImageBrush>
            <ImageBrush.ImageSource>
                <BitmapImage UriSource="//your source .."/>
            </ImageBrush.ImageSource>
        </ImageBrush>
    </Window.Background>
    
    0 讨论(0)
  • 2020-12-09 08:59
    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;
    
    0 讨论(0)
  • 2020-12-09 09:00

    What about this:

    new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))
    

    or alternatively, this:

    this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));
    
    0 讨论(0)
提交回复
热议问题