MVVM绑定viewmodel属性子项到viewmodel属性

4

我不确定我的标题是否能很好地解释我遇到的问题。

在我的应用程序中,我进行服务调用以 - 检索客户列表。 - 检索组织列表。

然后,我将这个客户列表绑定到我的视图上的列表框。

在我的视图模型中,我有以下属性:

IEnumerable<Organisation> Organisations 
ObservableCollection<Customer> Customers

组织属性: 组织ID,组织名称

客户属性: 客户ID,组织ID,客户名字,客户姓氏

在我的视图中的列表框内,我想要显示每个客户所属的组织名称。

我该如何在视图中进行绑定?我只需要一个文本块来显示客户所属的组织名称。


所以基本上你想要使用ID进行类似关系型数据库的名称查找? - H.B.
4个回答

4

我会将Model平铺在客户ViewModel中:

class CustomerViewModel : INotifyPropertyChanged
{
    public string OrgName { get; }
    public string FirstName {get; }
    public string LastName { get; }
}

接着,拥有的ViewModel返回了客户的集合:

public class StoreViewModel : INotifyPropertyChanged
{
    public ObservableCollection<CustomerViewModel> Customers { get; }
}

将ListBox绑定到CustomerViewModel的OrgName属性:
<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text="{Binding OrgName}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

0
将Listbox绑定到从您的ViewModel公开的Linq查询。
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}

};
}

然后只需将Ritch的答案中的列表框绑定到此处。

附言:我是在手机上写这篇文章的,所以代码可能不完美。


0
我会使用MultiBindingMultiValueConverter来实现这个功能,但如果您受限于Silverlight,那么很遗憾,这是不可能的,正如标签所示...

0

我同意Ritch的观点,你应该将模型展平,但如果你真的不想这样做,你可以使用IValueConverter。在绑定要显示名称的位置时,如果你将Organizations设置为另一个控件的数据上下文,你可以进行元素到元素的绑定,并在绑定中传递其他控件的数据上下文,在ConverterParameter中传递OrganizationId,然后在Converter代码中使用一些LINQ并返回你想要的名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接