我正在尝试使用存储过程和实体框架将数据加载到
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.
最佳答案 我不确定导致问题的原因,一般我建议使用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(如果添加或删除了Item,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;
}