【问题标题】:MVVM binding viewmodel property child to viewmodel propertyMVVM 将 viewmodel 属性子项绑定到 viewmodel 属性
【发布时间】:2011-08-26 20:22:13
【问题描述】:

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

在我的应用程序中,我调用了一个服务到 - 检索客户列表。 - 检索组织列表。

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

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

IEnumerable<Organisation> Organisations 
ObservableCollection<Customer> Customers

组织属性:OrganisationId、OrganizationName

客户属性:CustomerId、OrganisationId、CustomerFirstName、CustomerLastName

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

如何在我的视图中绑定它?我只想要一个文本块来显示客户的组织名称。

【问题讨论】:

  • 所以基本上你想要一个类似关系数据库的名称使用 ID 查找?

标签: wpf silverlight mvvm binding


【解决方案1】:

我会在客户 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>

【讨论】:

    【解决方案2】:

    我会为此使用MultiBinding 和MultiValueConverter,但遗憾的是,如果您像标签建议的那样受限于 Silverlight,这是不可能的...

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        将列表框绑定到从您的 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 的答案中的列表框绑定到此。

        PS。我在手机上写这个,所以代码可能不完美。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-25
          • 2011-02-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-30
          相关资源
          最近更新 更多