Wpf listview组合框绑定DisplayMemberPath无法正常工作

时间:2015-02-27 11:25:19

标签: wpf listview binding combobox

我有以下Wpf格式的代码:

public class Product
{
    public string Name { get; set; }
    public string Type { get; set; }
}

public class ProductWithValue
{
    public Product Object_Product { get; set; }
    public string Value { get; set; }
}

public class Data
{
    public ObservableCollection<Product> ListProduct { get; set; }
    public ObservableCollection<ProductWithValue> ListProdValue { get; set; }
}

Data data = LoadData();

lstProducts.DataContext = data;

XAML:

<ListView Name="lstProducts" ItemsSource="{Binding Path=ListProdValue}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Height="23">
                <ComboBox   ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.ListProduct}" 
                    SelectedItem="{Binding Path=Object_Product, Mode=TwoWay}" 
                    DisplayMemberPath="Name"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

LoadData示例:

private Data LoadData()
{
    Data data = new Data();

    Product prod1 = new Product(){Name="Name1", Type = "Type1"};
    Product prod2 = new Product(){Name="Name2", Type = "Type2"};

    data.ListProduct = new ObservableCollection<Product>()
    {
        prod1,
        prod2
    };

    data.ListProdValue = new ObservableCollection<ProductWithValue>()
    {
         new ProductWithValue(){ Object_Product = prod1, Value="Value"  }
    };

    return data;
}

Evrything很好,除了DisplayMemberPath。 组合框项目源是正确的,所选项目是正确的,但不显示产品名称。

任何想法都会出错?

1 个答案:

答案 0 :(得分:0)

我的代码中的错误LoadData函数:

private Data LoadData()
{
    Data data = new Data();

    Product prod1 = new Product() { Name = "Name1", Type = "Type1" };
    Product prod2 = new Product() { Name = "Name2", Type = "Type2" };
    Product prod3 = new Product() { Name = "Name3", Type = "Type3" };

    data.ListProduct = new ObservableCollection<Product>()
    {
        prod1,
        prod2,
        prod3
    };

    data.ListProdValue = new ObservableCollection<ProductWithValue>()
    {
        new ProductWithValue(){ Object_Product = new Product() { Name = "Name1", Type = "Type1" }, Value="Value1"  },
        new ProductWithValue(){ Object_Product = new Product() { Name = "Name2", Type = "Type2" }, Value="Value2"  }
    };

    return data;
}