Search code examples
wpfpowershelllistboxpsobject

Adding a PSObject to Listbox, but displaying only one of the properties


I want to add a PSObject, containing several properties, three to be exact, to a listbox, but only display one of the properties. When I add the entire PSobject to the listbox it shows all the properties like this:

@{Property1="Something", Property2="Something Else", Property3="Something"}

Let's say that property1 is the property I want the user to see, then that same objects row in the listbox shoud look like this:

Something

One way to solve this is to just add that specific property of the PSObject to the listbox instead, but I want each row to represent a unique object. So even if some of the PSObjects share their value of property1 with eachother, I would still be able to tell exactly which of the PSObjects is selected in the listbox. I can't know this if I only add a single property to the listbox.

For example there could be two objects having the value "Something" for their property1, but one of those has property2 set as "Something Else" and the other has it set as "A Third Something". The listbox should display the two objects identically, that is as:

Something
Something

but the listbox should know if the selected item has property2 set as "Something else" or "A Third Something", even if the user can't tell.


Solution

  • Try adding a ToString() script method to the PSObject which outputs the property in question.

    $p=[pscustomobject]@{a=1;b='hello'}
    $p | add-member -membertype ScriptMethod -name ToString -value {$this.b} -force
    

    When the item is added, the listbox will use its ToString() method to choose what to display.