CollectionViewSource 初始化引发列表框的 SelectionChanged
也许我错过了一些东西,但我已经对此感到头疼了。
我已经定义了 CollectionViewSource:
<CollectionViewSource x:Key="packagesViewSource" d:DesignSource="{d:DesignInstance my:Package, CreateList=True}" />
和 ListBox:
<ListBox Name="lstbPackages"
SelectionChanged="lstbPackages_SelectionChanged"
ItemsSource="{Binding Source={StaticResource packagesViewSource}}"
DisplayMemberPath="Name"
SelectedValue="{Binding Path=PackageId, UpdateSourceTrigger=Explicit}"
SelectedItem="{Binding Path=Package}"
SelectedValuePath="IdPackage"
/>
另外,我有代码隐藏的 packagesViewSource 初始化:
private IQueryable<Packages> GetPackagesQuery()
{
IQueryable<Package> query = dc.PackagesList;
// Returns an ObjectQuery.
return query;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
...
packagesViewSource =((System.Windows.Data.CollectionViewSource)(this.FindResource("packagesViewSource")));
queryPackages = this.GetPackagesQuery();
packagesViewSource.Source = queryPackages.ToList();
...
}
并且该行
packagesViewSource.Source = queryPackages.ToList();
涉及事件
private void lstbPackages_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
...
}
,正如您可以猜到
lstbPackages.SelectedItem != null
的那样。
我做错了什么?
May be I missed something, but I've already beat my head with this one.
I have defined CollectionViewSource:
<CollectionViewSource x:Key="packagesViewSource" d:DesignSource="{d:DesignInstance my:Package, CreateList=True}" />
and ListBox:
<ListBox Name="lstbPackages"
SelectionChanged="lstbPackages_SelectionChanged"
ItemsSource="{Binding Source={StaticResource packagesViewSource}}"
DisplayMemberPath="Name"
SelectedValue="{Binding Path=PackageId, UpdateSourceTrigger=Explicit}"
SelectedItem="{Binding Path=Package}"
SelectedValuePath="IdPackage"
/>
Also, I have code-behind packagesViewSource initialization:
private IQueryable<Packages> GetPackagesQuery()
{
IQueryable<Package> query = dc.PackagesList;
// Returns an ObjectQuery.
return query;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
...
packagesViewSource =((System.Windows.Data.CollectionViewSource)(this.FindResource("packagesViewSource")));
queryPackages = this.GetPackagesQuery();
packagesViewSource.Source = queryPackages.ToList();
...
}
And the line
packagesViewSource.Source = queryPackages.ToList();
involves event
private void lstbPackages_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
...
}
and as you could guess
lstbPackages.SelectedItem != null
there.
What I do wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将以下内容添加到您的 ListBox xaml 中。
Try adding the following to your ListBox xaml.
当您将源分配给 ListBox 时,将创建 packagesViewSource CollectionViewSource 的 DefaultView。并且它已选择第一个元素。因此,在分配源时,请分 3 步完成:
when you assign a source to your ListBox, a DefaultView of your packagesViewSource CollectionViewSource is created. and it has first element selected. So when assigning the source, do it in 3 step: