繁体   English   中英

如何在WPF图像控件中正确显示位图?

[英]How to properly show a bitmap in wpf Image control?

我有一个带有ListBox的表单,其中包含许多项目。 每个项目都应该具有标题和图像。 这是我的XAML:

 <ListBox x:Name="MyList" HorizontalAlignment="Left" Height="384" Margin="10,505,0,0" VerticalAlignment="Top" Width="366"
        ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <!--This works:-->
                    <Label Content="{Binding Title}"/>
                    <!--This doesn't:-->
                    <Image Width="50" Height="50" Source="{Binding Cover}" Stretch="UniformToFill"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我的数据类看起来像这样:

class Data
{
    public BitmapImage Cover{ get; set; }
    public string Title{ get; set; }
}

我从这样的Bitmap获取BitmapImage

Data data;//this is my data object
Bitmap bitmap;//this is my bitmap. It holds a valid image, I've checked.
MemoryStream memory = new MemoryStream();
bitmap.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
data.Cover = new BitmapImage();
data.Cover.BeginInit();
data.Cover.StreamSource = memory;
data.Cover.CacheOption = BitmapCacheOption.OnLoad;
data.Cover.EndInit();

最后,我像这样设置列表的数据:

MyList.ItemsSource = dataList;//dataList is a List<Data>

将标题(或其他简单的属性,如date或int属性)绑定到Label可以正常工作,但是图像不会显示。 如何使其正确显示?

因此,您的Data类中的Cover属性需要引发一个属性更改事件,以使视图知道它需要在更改后再次获取图像。 要做到这一点很简单:

class Data, INotifyPropertyChanged
{
     private BitmapImage _cover;
     public BitmapImage Cover
     {
        get { return _cover; }
        set 
        { 
            _cover = value;
            OnPropertyChanged("Cover");
        }
     }

    public string Title{ get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

您的Cover初始化代码在我的项目中工作正常。 我认为您忘记发布以下行:dataList.Add(data); 我不知道为什么要两次设置ItemsSource属性。 如果使用MVVM并绑定ItemsSource属性,则不应从代码中设置该属性(MyList.ItemsSource = dataList;)。相反,我建议在XAML中使用ItemsSource =“ {Binding} dataList”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM