ListView数据不会在WPF应用程序中刷新

时间:2013-10-03 16:58:32

标签: c# wpf entity-framework listview

我正在尝试使用存储过程和实体框架将数据加载到WPF中的ListView中。当我第一次加载用户控件时,ListView加载数据就好了。然后,我调用相同的代码来刷新数据,我可以通过调试看到ListItems计数发生了变化,但前端屏幕上的数据没有更新。

XAML

<ListView Name="DocsListView" ItemsSource="{Binding}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Documents" DisplayMemberBinding="{Binding Documents}"/>
        </GridView>
    </ListView.View>
</ListView>

背后的代码

public void LoadDocs()
{
    Context _Context = new Context();
    DocsListView.ItemsSource = null;
    DocsListView.ItemsSource = _Context.SP_GetDocuments(1).ToList();
    _Context = null;
}

有人可以帮我弄清楚我做错了什么吗?我正在使用VS2012,.Net 4.5和EF 5.0。

1 个答案:

答案 0 :(得分:2)

我不确定导致问题的原因,一般我建议使用DependencyProperty!

但您可以尝试刷新ListView:

ICollectionView view = CollectionViewSource.GetDefaultView(DocsListView.ItemsSource);
view.Refresh();

如果这是一个更大的项目,我强烈建议您查看MVVM DesignPattern!

WPF and MVVM一起玩得很好。你可以使用像MVVMLight这样的好文库。

另外,您应该查看INotifyPropertyChanged Interface

XAML-Code(不要忘记设置DataContext)

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <ListView Name="DocsListView" ItemsSource="{Binding Data}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Documents" DisplayMemberBinding="{Binding Documents}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

C#Code-Behind(如果添加或删除了某个项,ObservableCollection会自动刷新UI):

public ObservableCollection<YourEntity> Data
{
     get { return (ObservableCollection<YourEntity>)GetValue(DataProperty); }
     set { SetValue(DataProperty, value); }
}

// Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(ObservableCollection<YourEntity>), typeof(MainWindow), null);

public void LoadDocs()
{
     Context _Context = new Context();
     if(Data == null)
     {
         Data = new ObservableCollection<YourEntity>();
     }
     else
     {
         Data.Clear();
     }
     foreach(var doc in _Context.SP_GetDocuments(1).ToList())
     {
         Data.Add(doc);
     }
     _Context = null;
}