not sure if my title explains well the issue im having.
In my application i make a service calls to -retrieve a list of customers. -retrieve a list of organisations.
Then i bind this list of customers to a listbox on my view.
In my viewmodel i have the following properties:
IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers
Organisation properties: OrganisationId, OrganisationName
Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName
Inside the Listbox on my view i want to show the organisationname for each customer in the list.
how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.
I'd flatten the Model in a customer ViewModel:
class CustomerViewModel : INotifyPropertyChanged
{
public string OrgName { get; }
public string FirstName {get; }
public string LastName { get; }
}
Then the owning ViewModel returns the collection of Customers:
public class StoreViewModel : INotifyPropertyChanged
{
public ObservableCollection<CustomerViewModel> Customers { get; }
}
Bind the ListBox to the OrgName property on the CustomerViewModel:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding OrgName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我会为此使用MultiBinding
和MultiValueConverter
,如果你被限制为Silverlight,遗憾的是这不可能,因为标签建议...
I agree with Ritch that you should flatten the model, but if you really don't want to do that, you could use an IValueConverter. In the binding for where you want the name to be displayed, if you set Organizations to be the datacontext of another control, you could do element-to-element binding and pass the other control's datacontext in the binding, and in the ConverterParameter pass the OrganizationId, then in the Converter code use a little LINQ and return the Name you want
Bind the Listbox to a Linq query exposed from your ViewModel.
Public IEnumerable ItemsView
{
get {
return
{
from customer in this.Customers
from org in this.Organisations
where customer.OrganisationId=org.OrganisationId
select new { FirstName=customer.FirstName, LastName=customer.LastName, OrganisationName=org.OrganisationName}
};
}
Then just bind the listbox in Ritch's answer to this.
PS. I'm writing this on my phone so the code may not be perfect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.