Attach Image / ImageBrush from Code

I am trying to add an image as a UserControl background. Depending on the value of the variable, I need to change this background, but no matter which path or Uri format I use, the background does not change.

I saw a lot of questions here on stackoverflow, but not a single problem fixes my only problem. I give the code below:

if (callback.liveUvis.ContainsUVI(uvi)) { this.Status.Text = "LIVE"; ImageBrush imgB = new ImageBrush(); BitmapImage btpImg = new BitmapImage(); btpImg.UriSource = new Uri(@"///IMG///Live///bck_frame_info_video_live.png", UriKind.Relative); //imgB.ImageSource = new BitmapImage(new Uri("~/IMG/Live/bck_frame_info_video_live.png", UriKind.RelativeOrAbsolute)); //imgB.ImageSource = new BitmapImage(new Uri("ms-appx:///IMG/Live/bck_frame_info_video_live.png")); imgB.ImageSource = btpImg; this.Background = imgB; } 

I am facing the same problem when trying to attach an image ... I assume this also applies to the Uri format, but I also allow code just in case :)

  private void setIcon_Desc(string dd) { try { Image img = new Image(); img.Source = new BitmapImage(new Uri(this.BaseUri, "IMG/pictos_small/white/160dpi/" + dd + ".png")); img.Stretch = Stretch.None; this.Icon = img; this.Sport.Text = callback.disc.getDescription(dd).ToUpper(); } catch(Exception ex) { callback.exception.writeExceptions(ex); } } 

Thanks in advance!

+5
source share
1 answer

I can reproduce your problem when the background of the user control changes.

The current workaround I used is changing the background of the root UIElement in the control.

 <Grid x:Name="container"> <Grid.Background> <ImageBrush Stretch="Fill" ImageSource="Images/bg-blue.png"/> </Grid.Background> <StackPanel> <TextBlock>Hello World</TextBlock> <Button Click="Button_Click">Change Background</Button> <Image x:Name="display"></Image> </StackPanel> </Grid> 

 public sealed partial class MyUserControl : UserControl { public MyUserControl() { this.InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ImageBrush imgB = new ImageBrush(); BitmapImage btpImg = new BitmapImage(); btpImg.UriSource = new Uri(@"ms-appx:///images/bg-light-blue.png"); imgB.ImageSource = btpImg; container.Background = imgB; } } 
+4
source

Source: https://habr.com/ru/post/1233761/


All Articles