I’m creating a custom UserControl for a DataTemplate that takes in a Metadata object and assigns the FilePath to an Image (these paths are defined by the user at runtime). However, despite throwing no errors and ensuring the Image’s source is correct and leads to an actual file, the image does not appear during run time. I put a border around the image and that shows up, but the image does not.
Here’s the XAML code for the UserControl:
<Border x:Name="Outline"
BorderThickness="1"
BorderBrush="Red">
<Grid>
<Image x:Name="DisplayImage"/>
<MediaElement x:Name="DisplayVideo"/>
</Grid>
</Border>
And the code behind where the image’s source is set:
public MediaContainer() {
InitializeComponent();
Loaded += (_, _) => Load();
}
private void Load() {
Metadata data = (Metadata)DataContext;
(double height, double width) = Scale(data); // This never returns 0, for either the height or the width
Outline.Width = width + (Configs.OUTLINE_WIDTH * 2);
Outline.Height = height + (Configs.OUTLINE_WIDTH * 2);
Uri uri = new(data.FilePath, UriKind.RelativeOrAbsolute);
BitmapImage source = new(uri);
DisplayImage = new() {
Source = data.FileType == FileType.Gif ? null : source,
Height = height,
Width = width
};
static (double, double) Scale(Metadata meta) {
double _height = meta.Height <= 0 ? Configs.HEIGHT : meta.Height;
double _width = meta.Width <= 0 ? Configs.HEIGHT : meta.Width;
if (meta.Height != Configs.HEIGHT) {
double scale = Configs.HEIGHT / meta.Height;
_height = Configs.HEIGHT;
_width = meta.Width * scale;
}
return new(_height, _width);
}
}
I’ve attempted to manually set the z-index of the image and media element, but to no avail. So what’s preventing it from being displayed?
>Solution :
You must not assign a new value to the DisplayImage field. Instead, set the properties of the existing Image control:
DisplayImage.Source = data.FileType == FileType.Gif ? null : source;
DisplayImage.Height = height;
DisplayImage.Width = width;
You must also make sure that the Image element lies on top of the MediaElement, or that the MediaElement is invisible when an image is shown, e.g by setting
DisplayVideo.Visibility = Visibility.Collapsed;
