我如何在列表框上使用这样的代码?
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} + {1}">
<Binding Path="Name" />
<Binding Path="ID" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
我想在列表框上执行以上操作。我的数据源有两个项目,名字和姓氏,我想同时显示两者。我尝试了这个,但是没有用:
<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>
请注意,我想像上面那样使用xaml,而不是单独的IConverter类或其他东西。
最佳答案
代替DisplayMemberPath
使用自定义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>