An Hoa
An Hoa

Reputation: 1267

Programatically build UI for ListView's items

From various questions, I know it is impossible to create DataTemplate from the code behind without using the XamlReader. So I want to ask if there is a way to programatically generates the UI for each Item in a ListView. I don't seem to find any relevant event handler or member of ListView for this purpose. Ideally, I want the ListView to invoke my handler code to generate UI for each data item it needs to display.

Upvotes: 0

Views: 54

Answers (2)

An Hoa
An Hoa

Reputation: 1267

Imitating the official XamlTreeView sample, I have tried overriding some ListView method such as PrepareContainerForItemOverride but this won't work. The solution I found is as @JustinXL suggests: producing ListViewItem and insert them to the ListView->Items directly

//assume that items is a list of items we want to bind
myListView->Items->Clear();
for(auto i : items)
{
     ListViewItem^ v = ref new ListViewItem();
     v->Content = GenerateUIFor(i);
     myListView->Items->Append(v); // NOTE: a wrapping ListViewItem is required!
}

To support usual data binding, it would be best to make the data structure to cache the generated UI. For example,

ref class MyDataStructure
{
public:
    property ListViewItem^ Item
    {
        ListViewItem^ get()
        {
             if (_item == nullptr)
                 GenerateUI();
             return _item;
        }
    }
    void GenerateUI()
    {
        _item = ref new ListViewItem();
        _text_block = ref new TextBlock(); // sample
        _item->Content = _text_block;
        UpdateUI();
    }

    // Invoke this when changing the state of this object
    void UpdateUI()
    {
        if (_text_block != nullptr) // sample
        {
             _text_block->Text = this->ToString(); // sample
        }
    }
private:
    ListViewItem^ _item;
    TextBlock^ _text_block;
};

The downside of this is of course we can't make use of data virtualization. But it works properly for small set of data. For large set, one can use website's approach with Next and Prev button to load next page or go back to previous page.

Upvotes: 1

Hippiehunter
Hippiehunter

Reputation: 975

ItemContainerGenerator should let you construct the entire UI for an item inside a list view. Unfortunately there doesn't appear to be much in the way of non MSDN documentation/samples for this.

Alternatively if you can maintain a list of all the DataTemplates you might need to show, you could use a DataTemplateSelector to choose which DataTemplate you want to show for each individual item.

Upvotes: 0

Related Questions