【问题标题】:Wpf listview combobox binding DisplayMemberPath not workingWpf listview组合框绑定DisplayMemberPath不起作用
【发布时间】:2015-02-27 11:25:18
【问题描述】:

我有以下 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>

加载数据示例:

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;
}

一切都很好,除了 DisplayMemberPath。 组合框 itemssource 正确,选择的 item 正确,但不显示产品名称。

知道怎么回事吗?

【问题讨论】:

  • XAML 代码看起来没问题,您可以将问题代码添加到LoadData 方法吗?
  • 你看到了什么?任何对象路径或空白?
  • 我只看到一个空白字段。
  • LoadData 只是用数据填充列表,一切正常。
  • @KishonthyMárton 截取您的视图并添加到问题中。

标签: wpf listview binding combobox


【解决方案1】:

我的代码中有错误的 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2018-02-20
    • 2011-08-19
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多