首页 > 解决方案 > 有时 ListView 中的图像会消失

问题描述

带有国旗的国家列表显示在 ListView 中。标志显示为带有填充 ImageBrush 的椭圆。

<ControlTemplate TargetType="ContentControl">
    <StackPanel Orientation="Horizontal" Background="Transparent">
        <Ellipse Width="23" Height="23" StrokeThickness="1" Stroke="#2F7AE5" Fill="{Binding FlagBrush}"/>                                 
        <TextBlock Text="{Binding Path=Country}" 
            Foreground="{StaticResource HBBtnTextBrush}" FontSize="16" FontWeight="Bold" 
            VerticalAlignment="Center" Margin="14,0,0,0"/>
        <ContentPresenter/>
    </StackPanel>
</ControlTemplate>


public ImageSource FlagImage { get => Flag.GetImage(country_code); }

ImageBrush flagBrush;
public ImageBrush FlagBrush {
    get
    {
        if (flagBrush == null)
        {
            flagBrush = new ImageBrush
            {
                ImageSource = FlagImage,
                Stretch = Stretch.UniformToFill
            };
            flagBrush.Freeze();
        }
        return flagBrush;
    }            
}

列表隐藏部分中的一两个图像消失。图像作为带有 GeometryDrawing 的 DrawingImage 存储在资源中。如果你转到另一个页面然后返回这些图像会出现,但其他的可能会消失。在调试器中,这些图像是 ImageSource 中固有的,如果您更改任何图像参数,例如位置或调整大小,图像会立即出现。

例子

在 Live Property Explorer 中

标签: wpflistviewbindingimagebrush

解决方案


用肮脏的黑客解决了这个问题。我将 WrapPanel 添加到屏幕的空白区域,并在那里显示所有可能的 1x1 像素和 Opacity=0.01 的标志。在那之后,消失的标志就没有问题了。


推荐阅读