从后面的代码附加 Image/ImageBrush

Attach Image/ImageBrush from code behind

我正在尝试添加图像作为 UserControl 的背景。根据变量的值,我需要更改该背景,但无论我使用什么路径或 Uri 格式,背景都不会改变。

我在 Whosebug 中看到了很多问题,但 none 解决了我的一个问题。 我让下面的代码:

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

我在尝试附加图像时遇到了同样的问题...我想这也取决于 Uri 格式,但我也放了代码以防万一:)

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

    }

提前致谢!

我可以在更改用户控件的背景时重现您的问题。

我目前使用的解决方法是更改​​控件中根 UIElement 的背景。

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