Stamatis Stiliats
Stamatis Stiliats

Reputation: 399

UWP Programatically change background image of XAML page c#

I have been searching for a while and honestly I haven't solved this really simple issue. I have a flyout menu and I have attached an event to a flyout menu item. I want to change programmatically the background image of my XAML page when I select the item.

<Grid x:Name="main">
    <Grid.Background>
        <ImageBrush Stretch="Fill" ImageSource="Assets/bg_1.jpg"/>
    </Grid.Background>
</Grid>

This is the default image I got as a background (the grid is basically the whole page).

The C# event code is here:

private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{
    main.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri("ms-appx:///MTG Life Counter/Assets/bg_2.jpg")) , Stretch = Stretch.None};
}

When I select the menu item instead of setting the image as background, it makes it white.

Default background

I tested and it is not an issue of the image. I know that I am doing something like an obvious mistake but I am a bit new to UWP and I couldn't find a solution.

Here is the blank background after I select to change it

Thanks for you time and sorry for the ignorance.

Upvotes: 5

Views: 7382

Answers (1)

Dark Templar
Dark Templar

Reputation: 1155

there's a property called "BaseUri"... try adding it to your code.

make these changes:

    private void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
    {
        main.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(this.BaseUri, "Assets/bg_2.jpg")), Stretch = Stretch.None };
    }

Upvotes: 4

Related Questions