0

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.

Viktor Axén
  • 199
  • 2
  • 11
  • Viktor Axén, please edit your post and add the code that you are running. If we cannot see the code then we won't know what is going wrong in your program. Thanks – cet51 Feb 12 '18 at 15:37
  • 2
    Have you tried adding `DisplayMemberPath="Property1"` to the `ListBox` control in the markup? – Mathias R. Jessen Feb 12 '18 at 15:42
  • @CoryEtmund, nothing is really going wrong in my code, the problem is that i have no idea how to write the code that does what I want. My current code is working, just not for the purpose I intended. – Viktor Axén Feb 12 '18 at 16:29
  • How and where are you creating the actual ListBox in your code? – mm8 Feb 12 '18 at 16:36

1 Answers1

0

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.

Mike Shepard
  • 17,466
  • 6
  • 51
  • 69