JoeMjr2
JoeMjr2

Reputation: 3944

WPB ListBox bind to control inside a class

I have a WPF ListBox of Grids that I create as follows:

I define the listbox in XAML with a simple declaration as follows:

<ListBox Name="MyListbox" >
</ListBox>

In code, I dynamically create an arbitrary number of Grid items (System.Windows.Controls.Grid), and I add them to the ListBox. Something like:

foreach (MyDataType myItem in MyDataList)
{
   Grid newGrid = new Grid();
   // Code that sets the properties and values of the grid, based on myItem

   MyListbox.Items.Add(newGrid);
}

This works great, and everything looks the way that I want it to.

Now, I've decided that in my ListBox, I also want to store a reference to the actual myItem object, so that I can reference it later.

My idea was to create a new class like:

public class ListGridItemNode
{
    public MyDataType theItem;
    public Grid theGrid;
    public ListGridItemNode(MyDataType inItem, Grid inGrid)
    {
        theItem = inItem;
        theGrid = inGrid;
    }
}

And then change my code to:

foreach (MyDataType myItem in MyDataList)
{
   Grid newGrid = new Grid();
   // Code that sets the properties and values of the grid, based on myItem

   MyListbox.Items.Add(new ListGridItemNode(myItem,newGrid));
}

Of course, now my listbox instead of displaying the grids, just displays the text "MyApp.ListGridItemNode".

My question is: How do I tell the ListBox to go a level deeper and display the actual Grids inside of each ListGridItemNode object?

I suspect that this has something to do with bindings, but I can't find any examples that work the way that I'm doing it. Most of what I'm finding only shows binding to a string within an object, not an entire control.

Upvotes: 0

Views: 66

Answers (1)

AlfieJ
AlfieJ

Reputation: 369

Couldn't you just use the Tag property of the Grid object?

newGrid.Tag = myItem;

Then later:

Grid grid; // obtain Grid object somehow
MyItem myItem = (MyItem) grid.Tag;

Upvotes: 1

Related Questions