代码之家  ›  专栏  ›  技术社区  ›  Terminal2772

以编程方式设置的图像在运行时不显示

  •  0
  • Terminal2772  · 技术社区  · 2 年前

    我正在为DataTemplate创建一个自定义UserControl,它接受元数据对象并将FilePath分配给图像(这些路径由用户在运行时定义)。但是,尽管没有抛出任何错误,并确保图像的来源是正确的,并导致生成实际的文件,但图像在运行时不会出现。我在图像周围加了一个边框,它就会显示出来,但图像没有。

    An outline of a red rectangle. There is no image contained within it.

    以下是UserControl的XAML代码:

    <Border x:Name="Outline"
            BorderThickness="1"
            BorderBrush="Red">
        <Grid>
            <Image x:Name="DisplayImage"/>
            <MediaElement x:Name="DisplayVideo"/>
        </Grid>
    </Border>
    

    以及设置图像源的代码:

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

    我曾尝试手动设置图像和媒体元素的z索引,但没有成功。那么,是什么阻止了它的显示呢?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Clemens    2 年前

    不能将新值分配给 DisplayImage 领域相反,设置现有图像控件的属性:

    DisplayImage.Source = data.FileType == FileType.Gif ? null : source;
    DisplayImage.Height = height;
    DisplayImage.Width = width;
    

    您还必须确保Image元素位于MediaElement的顶部,或者在显示图像时MediaElement是不可见的,例如通过设置

    DisplayVideo.Visibility = Visibility.Collapsed;
    
    推荐文章