Question

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?

Was it helpful?

Solution

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:

  1. Get DefaultView for your resource, then
  2. MoveCurrentToPosition(-1) on this view, then
  3. assign the View with correct current position to ListBox.

OTHER TIPS

Try adding the following to your ListBox xaml.

IsSynchronizedWithCurrentItem="false"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top