变化

2010-03-06 26 views
0

HI后动态更新WPF的ListView 我有这样的代码变化

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> 

这个片段是修改myListView 元素的occrnce的数量,当我点击该按钮,并使这些更改myListView不会改变。任何帮助请 - 是缺少的东西?

+0

您在哪里将ListView的DataContext设置为集合。最好将ObservableCollection保留在Click处理程序之外 – 2010-03-07 00:10:16

回答

2

如果您的代码与您展示的代码完全相同,这是因为您正在创建一个新的ObservableCollection,它对Button_Click方法是本地的,并让它超出范围。您需要将DataContext设置为新集合,或者(更习惯)修改作为现有DataContext的集合的元素。

如果您采用第一个选项,则需要修复代码,因为LINQ查询正在运行新的(空)集合,并且将始终返回空值。

如果您已经在执行第二个选项,或者更改了代码以使用第二个选项,则仍然存在问题,因为ListProduct没有引发属性更改通知。因此,当您修改number属性时,WPF无法检测到此更改并更新绑定。

要解决此问题,请在ListProduct类上实现INotifyPropertyChanged,然后更新属性设置器以引发PropertyChanged事件。 (您将而不是能够使用C#自动属性;您必须手工实现属性获取器和设置器。)