Reputation: 261
Let me start off by saying that I am very new to WPF and LINQ and have been struggling to learn it while working on a project with it at work (don't you hate having to learn things on the fly and complete the project before a deadline!). Anyway, I have a list box of employees that is being bound in the code behind to an ObservableCollection The datasource for the collection is a LINQ query of type IQueryable.
What I am trying to do is show the LastName + " ," + FirstName format on the listbox, and I am not sure how to pull that off. It will be just for display and does not affect the data in any way. I have tried using the select new syntax for LINQ, however, it does not work because the query is returning an IQueryable and the field does not belong to Employee. The objects in the listbox need to be Employee objects because they can then be saved back to the database or moved to other listboxes in the form for different reasons.
I am not sure where to go form here, and I am sorry if I don't make myself very clear. If you have any further questions about what I need to do, please ask away and I will try to answer. Thanks!
Upvotes: 3
Views: 2361
Reputation: 50028
You can do a multibinding and StringFormat to do this very easily and with less visual cost. In your ListBox
<ListBox ItemsSource="{Binding EmployeeCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock >
<TextBlock.Text >
<MultiBinding StringFormat=" {0},{1} ">
<Binding Path="LastName" />
<Binding Path="FirstName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Upvotes: 2
Reputation: 310822
Assuming you have an ObservableCollection<Employee>
, where Employee
is a type with LastName
and FirstName
properties, then something like this should work:
<ListBox ItemSource="{Binding Employees}">
<ListBox.Resources>
<DataTemplate TargetType="{x:Type local:Employee}">
<StackPanel>
<TextBlock Text="{Binding Path=LastName}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding Path=FirstName}" />
<StackPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
The ListBox tries to display its items, but Employee
is not a UIElement
, so it searches for a template that describes the presentation of the type. There's a DataTemplate
embedded in the ListBox
's resources that does just that.
Upvotes: 1