[英]WPF Listview not displaying when I add an item
I'm trying to add items dynamically to a listview in WPF, but I don't know why any items are displaying.我正在尝试将项目动态添加到 WPF 中的列表视图,但我不知道为什么显示任何项目。 Though it was a refresher problem, so I tried to use some ObservableCollection but it didn't work.
虽然这是一个复习问题,所以我尝试使用一些 ObservableCollection 但它没有用。 I'm getting informations in two textblocs, and want them to show in the listview when I click on a button.
我在两个文本块中获取信息,并希望它们在我单击按钮时显示在列表视图中。
Could you help me understund the problem?你能帮我理解这个问题吗?
My WPF with the listview我的 WPF 与列表视图
<ListView Name="listview" Margin="0 10 0 0" Height="150" ItemsSource="{Binding Recette}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding nomP}" Header="Nom" Width="250"/>
<GridViewColumn DisplayMemberBinding="{Binding quantP}" Header="Quantité" Width="100"/>
</GridView>
</ListView.View>
</ListView>
My.cs:我的.cs:
public List<Produits> Recette { get; set; }
public AjoutRecette()
{
InitializeComponent();
}
private void btnAjoutProd_Click(object sender, RoutedEventArgs e)
{
string nomP = combobProd.Text;
int quantP = int.Parse(txtbQuantité.Text);
Produits prod = new Produits(nomP, quantP);
Recette.Add(prod);
}
and here's what i've already tried with the ObersvableCollection:这是我已经尝试过的 ObersvableCollection:
public ObservableCollection<Produits> Recette { get; set; }
public AjoutRecette()
{
InitializeComponent();
}
private void btnAjoutProd_Click(object sender, RoutedEventArgs e)
{
Recette = new ObservableCollection<Produits>();
string nomP = combobProd.Text;
int quantP = int.Parse(txtbQuantité.Text);
Produits prod = new Produits(nomP, quantP);
Recette.Add(prod);
}
Thanks a lot !非常感谢 !
To make it work, please check the following points:要使其正常工作,请检查以下几点:
Please change Recette
to be of type ObservableCollection<Produits>
instead of List<Produits>
.请将
Recette
更改为ObservableCollection<Produits>
类型,而不是List<Produits>
。 You would need to adjust the property type as well as the part of code where you instantiate the collection.您需要调整属性类型以及实例化集合的代码部分。 You can simply do:
你可以简单地做:
public ObservableCollection<Produits> Recette { get; set; } = new ObservableCollection<Produits>();
Make sure that the DataContext
property is set correctly.确保
DataContext
属性设置正确。 One way of doing that would be to set DataContext
in the constructor of AjoutRecette
:一种方法是在
AjoutRecette
的构造函数中设置DataContext
:
public AjoutRecette() { InitializeComponent(); listview.DataContext = this; }
Also, please make sure that properties nomP
and quantP
are present in the Produits
class.另外,请确保产品
quantP
中存在属性nomP
和Produits
。
Good luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.