首页 > 解决方案 > WPF - 如何在 ICollectionView 位图图像中显示?

问题描述

所以我有一个List<Book>包含一个BitmapImage.

我有一个从一个这样初始化的DataGrid它获取它的信息:ICollectionView

ObservableCollection<Book> OCBooks = new ObservableCollection<Book>();
CollectionViewSource BooksCollection;
Predicate<object> yourCostumFilter;
ICollectionView Itemlist;
Book b = Book.Instance;

. . .

private void InitializeObservableCollection()
        {
            foreach (var item in ChangeBooksImagesToBitmapImage(b.GetBooksList()))
                OCBooks.Add(item);
            BooksCollection = new CollectionViewSource { Source = OCBooks };
            Itemlist = BooksCollection.View;
            DG_BooksList.ItemsSource = Itemlist;
        }

. . .

private List<Book> ChangeBooksImagesToBitmapImage(List<Book> list)
        {
            // takes a Books list with imgURLs and returns one with BitmapImage
            List<Book> newbl = new List<Book>();
            foreach (var book in list)
            {
                if (!string.IsNullOrEmpty(book.ImgURL))
                {
                    BitmapImage logo = new BitmapImage();
                    logo.BeginInit();
                    logo.UriSource = new Uri(book.ImgURL);
                    logo.DecodePixelHeight = 25;
                    logo.DecodePixelWidth = 25;
                    logo.EndInit();
                    newbl.Add(
                        new Book(
                            book.BookName,
                            book.Genre,
                            DateTime.Parse(book.Published.ToShortDateString()),
                            book.Publisher,
                            logo,
                            book.Quantity));
                }
                else
                    newbl.Add(book);
            }
            return newbl;
        }

我以前只使用了一个常规列表并将其逐列绑定到 ,DG_BooksList因此我将能够操作这些列并且它可以工作。

当我想为列表创建过滤器时,我明白使用ICollectionView可能是更好的方法。

DataGrid只是现在我不知道如何操作When It's automatically give it the information中的每一列。

我试图寻找答案但找不到,我如何DataGrid像这样操作单列以及如何BitmapImageDataGrid?

标签: c#wpf

解决方案


如果您的 Book 类型包含公共属性 Logo 并且还实现了 INotifyPropertyChanged.. 您可以使用 DataGridTemplateColumn 并为其指定 dataTemplate

<DataGridTemplateColumn Header="Logo">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Image Source="{Binding Logo}" Height="25" Width="25"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

推荐阅读