Search code examples
c#listboxlistboxitem

Multiselect listbox item returning system.windows.controls.listboxitem: with the listboxitem value


Listboxitems that are selected return system.windows.controls.listboxitem: ExampleValue.

private void Trade_SelectionChanged(object sender, SelectionChangedEventArgs e)
   {
        TradesSelected.Text = "";
        foreach (object trade in Trade.SelectedItems)
      {
        TradesSelected.Text += (TradesSelected.Text == "" ? "" : ",") + trade.ToString();
      }
    }

How can you remove the system.windows.controls.listboxitem: part so it will just show ExampleValue?

<StackPanel>
                    <TextBox x:Name="TradesSelected" Width="300" Padding="2" ></TextBox>
                    <ListBox SelectionMode="Multiple" x:Name="Trade" Width="300" Height="100" Padding="2" SelectionChanged="Trade_SelectionChanged">
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="ListBoxItem">
                                <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
                            </Style>
                        </ListBox.ItemContainerStyle>
                        <ListBoxItem>ExampleOne</ListBoxItem>
                        <ListBoxItem>ExampleTwo</ListBoxItem>
                        <ListBoxItem>ExampleThree</ListBoxItem>
                    </ListBox>
                </StackPanel>

Solution

  • You need to cast your trade object to the type it actually is. The .ToString() method of the object type simply returns the type name. See here.

    Also, probably the type that the trade object really is, has a property/field/method that returns the string value that you actually want to show.

    TradesSelected.Text += (TradesSelected.Text == "" ? "" : ",") + (trade as ListBoxItem).Content.ToString();