Attach Image/ImageBrush from code behind

后端 未结 1 1893
执笔经年
执笔经年 2021-01-06 02:11

I\'m trying to add an Image as the background of a UserControl. Depending on the value of a variable I need to change that background but whatever the path or Uri format I u

相关标签:
1条回答
  • 2021-01-06 02:37

    I can reproduce your issue when changing the background of a user control.

    The current workaround I used was changing the background of 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题