Reputation: 113
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?
Upvotes: 2
Views: 1263
Reputation: 366
Try adding the following to your ListBox xaml.
IsSynchronizedWithCurrentItem="false"
Upvotes: 3
Reputation: 19294
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:
Upvotes: 1