[英]Wpf listview combobox binding DisplayMemberPath not working
我有以下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除外。 組合框項目來源正確,所選項目正確,但未顯示產品名稱。
知道發生了什么事嗎?
我的代碼中錯誤的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.