简体   繁体   中英

How should I set an image index of an ImageListBox item in a databinding scenario?

I have a Document object that looks like this:

public class Document
{
    public Title { get; set; }
    public Extension { get; set; }
    public byte[] Data { get; set; }
}

The Extension is "pdf", "doc", "docx" and the like. This document is used for storing documents in a database (it's actually a DevExpress XPO object).

The problem I'm having is, I am binding a list of these objects to an imagelistbox, which has an associated image list of the icons to display for each file type. How can I set the image index on the imagelistbox item based on the Extension without storing the index in the domain object?

In WPF, I would have used the MVVM pattern to solve that issue : the XPO object wouldn't be directly used by the UI, instead a ViewModel object would expose the necessary properties so that they can easily be used in binding scenarios. MVVM is specific to WPF, but I believe the MVP pattern is very similar and can easily be used in Windows Forms. So, you could create a Presenter object which would act as an adapter between the UI and the XPO object :

public class DocumentPresenter
{
    private Document _document;

    public DocumentPresenter(Document document)
    {
        _document = document;
    }

    public string Title
    {
        get { return _document.Title; };
        set { _document.Title = value; };
    }

    public string Extension
    {
        get { return _document.Extension; };
        set { _document.Extension = value; };
    }

    public byte[] Data
    {
        get { return _document.Data; };
        set { _document.Data = value; };
    }

    public int ImageIndex
    {
        get
        {
            // some logic to return the image index...
        }
    }

}

Now you just have to set the DataSource to a collection of DocumentPresenter objects, and set the ImageIndexMember to "ImageIndex"

Disclaimer : I never actually used the MVP pattern, only MVVM, so I might have got it wrong... anyway, you get the picture I guess ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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