Search code examples
wpflistboxmultibinding

MultiBinding on a WPF Listbox


How can i use code like this on a listbox???:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

I want to do the above on a listbox. My datasource has two items, forenames and surname and i want to display both. i tried this but its not working:

<ListBox ItemsSource="{Binding}" Name="listBox" Width="200" DockPanel.Dock="Left" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch" SelectionChanged="selectionChanged" >
                <ListBox.DisplayMemberPath>
                    <MultiBinding StringFormat="{}{0} + {1}">
                        <Binding Path="forenames" />
                        <Binding Path="surname" />
                    </MultiBinding>
                </ListBox.DisplayMemberPath>
            </ListBox>

Please note i want to use xaml like above and not a separate IConverter class or something.


Solution

  • Instead of DisplayMemberPath use custom ItemTemplate

    <ListBox ItemsSource="{Binding}" Name="listBox" Width="200" DockPanel.Dock="Left" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch" SelectionChanged="selectionChanged" >
       <ListBox.ItemTemplate>
          <DataTemplate>
             <TextBlock>
                <TextBlock.Text>
                   <MultiBinding StringFormat="{}{0} + {1}">
                      <Binding Path="forenames" />
                      <Binding Path="surname" />
                   </MultiBinding>
                </TextBlock.Text>
             </TextBlock>
          </DataTemplate>
       </ListBox.ItemTemplate>
    </ListBox>