将UWP ComboBox的ItemsSource设置为ViewModel属性

时间:2016-12-02 00:18:58

标签: xaml uwp uwp-xaml

我正在尝试将UWP ComboBox的ItemsSource设置为ViewModel的属性,但是我收到错误:

Error: BindingExpression path error: 'componentsLookup' property not found on 'Orders.Component'

XAML的相关部分如下所示:

<Page.DataContext>
    <local:OrderPageViewModel x:Name="OrderPageViewModel" />
</Page.DataContext>

<ListView
    Name="ComponentsList"
    ItemsSource="{Binding Components}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <ComboBox
                    ItemsSource="{Binding componentsLookup,Mode=TwoWay}"
                    DisplayMemberPath="ComponentCode"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel的相关位如下所示:

public class OrderPageViewModel
{
    public ObservableCollection<Product> Products { get; set; } = new ObservableCollection<Product>();
    public List<Component> componentsLookup = new List<Component>();

编辑1:模型看起来像这样

public class Product
{
    public string ProductCode { get; set; }
    public string ProductDescription { get; set; }
    public List<Component> Components { get; set; }
    public override string ToString()
    {
        return this.ProductCode;
    }
}
public class Component
{
    public Guid ComponentId { get; set; }
    public Product Product { get; set; }
    public string ComponentCode { get; set; }
    public string ComponentDescription { get; set; }
    public string ComponentColor { get; set; }
    public decimal  ComponentHeight { get; set; }
    public decimal ComponentWidth { get; set; }
    public override string ToString()
    {
        return this.ComponentCode;
    }
}

如何将ItemsSource设置为componentsLookup

1 个答案:

答案 0 :(得分:2)

嵌套绑定是您实际想要做的事情。由于duplex嵌套在ComboBox内,ListView的{​​{1}}需要是ItemsSource的子集合。 ComboBox应该是代码段中ListView类的属性。您可以使用嵌套的源结构,如下所示进行绑定:

componentsLookup

XAML代码

Orders.Component

更多详情请参阅official data binding document