WPF列表框上的MultiBinding

时间:2014-05-23 10:25:15

标签: wpf listbox multibinding

如何在列表框上使用这样的代码???:

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

我想在列表框中执行上述操作。我的数据源有两个项目,forenames和surname,我想显示两者。我试过这个,但它不起作用:

<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类或其他东西。

1 个答案:

答案 0 :(得分:6)

而不是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>