更改后动态更新WPF ListView

时间:2010-03-06 23:03:49

标签: wpf

HI 我有这个代码

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上元素的隐藏次数 当我单击按钮并进行更改时myListView不会更改。请帮助 - 缺少什么?

1 个答案:

答案 0 :(得分:2)

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

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

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

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