Reputation: 4941
HI I have this code
private void Button_Click(object sender, RoutedEventArgs e)
{
ObservableCollection<ListProduct> myList = new ObservableCollection<ListProduct>();
int index = myList.IndexOf((from parcour in myList
where parcour.name == myProduct.name
select parcour).FirstOrDefault());
if(index != -1)
{
myList[index].number++;
}
}
public class ListProduct
{
public string name { get; set; }
public int number{ get; set; }
}
XAML:
<ListView Name="ListView12" ItemsSource="{Binding}" Height="201">
<ListView.View>
<GridView>
<GridViewColumn Width="100" Header="name"
DisplayMemberBinding="{Binding name}" />
<GridViewColumn Width="100" Header="number"
DisplayMemberBinding="{Binding nombre}" />
</GridView>
</ListView.View>
</ListView>
this snippet is to modify the number of occrnce of an element on myListView when I click the button and made those change myListView do not change. Any Help please -- is something missing?
Upvotes: 1
Views: 1090
Reputation: 74842
If your code is exactly as you show it, this is because you are creating a new ObservableCollection which is local to the Button_Click method, and letting it go out of scope. You need to either set the DataContext to the new collection, or (more idiomatic) modify the elements of the collection which is your existing DataContext.
If you adopt the first option, you'll need to fix the code, because the LINQ query is running over the new (empty) collection and will always return null.
If you're already doing the second option, or change you code to use the second option, you still have a problem because ListProduct is not raising property change notification. So when you modify the number
property, WPF has no way of detecting this change and updating the binding.
To fix this, implement INotifyPropertyChanged on the ListProduct class, and update your property setters to raise the PropertyChanged event. (You will not be able to use C# automatic properties; you must implement the property getters and setters by hand.)
Upvotes: 2