问题
The following shows me 3x "MultiTest.Model.Customers" in the ListBox (one for each record it should display).
What do I need to change in order for it to output the contents of the fields instead?
<Window.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ContentTemplate" >
<Setter.Value>
<MultiBinding StringFormat="{}{1}, {0} ">
<Binding Path="FirstName" />
<Binding Path="LastName"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListBox x:Name="theCustomers"/>
</Grid>
binding in code-behind with ADO.NET Entity Framework:
MainEntities db = new MainEntities();
var customers = from c in db.CustomersSet
select c;
theCustomers.ItemsSource = customers;
ANSWER:
Thanks, Steve, here is your answer in my Window.Resources format:
<Window.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ContentTemplate" >
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{1}, {0} ({2})">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
<Binding Path="ID"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListBox x:Name="theCustomers"/>
</Grid>
回答1:
If you particularly want to use MultiBinding you should be able to use a DataTemplate with StringFormat.. something like:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{1}, {0}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Or for something more complicated you could use a ValueConverter (or the multiple binding variant).
回答2:
I've never used MultiBinding before. I have used, however, DataTemplates:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBlock Text=" - "/>
<TextBlock Text="{Binding Email}" Margin="5,0"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Hope this helps!
来源:https://stackoverflow.com/questions/577697/how-can-i-get-multibinding-to-work-in-xaml-listbox