ListBox TwoWay Binds to SelectedItem

I saw this question many times and iterated over the code again and again. But when I bind to the SelectedItem-bound property with an object, it does not update the selected display element. It seems to ListBoxbelieve that the object that I am assigning is not a member of its elements.

public class MainViewModel : ViewModelBase
{
    //...
    public SortedObservableCollection<TubeViewModel> Items { get; private set; }
    public TubeViewModel SelectedTube { //get, set, propertychanged, etc. }
}

<ListBox x:Name="TubeList"
         Margin="10"
         ItemsSource="{Binding Items}"
         ItemTemplate="{StaticResource TubeTemplate}"
         SelectedItem="{Binding SelectedTube, Mode=TwoWay}" 
         SelectionMode="Single"
         VirtualizingStackPanel.IsVirtualizing="False">
</ListBox>

Here, the impl from one of the places where I am trying to install SelectedTubeis definitely found in the main thread.

 var match =
    from t in Items
    where t.Model.DataFileName == filename
    select t;
 if (match.Any())
    SelectedTube = match.First();

I noticed that SelectedTubeI never stood out unless I clicked manually, but ignored it. But then I wanted the ScrollIntoViewCentered selected item, so I added DependencyPropertyin my opinion to keep track of the changes SelectedItem. The handler first looked like this:

private void OnSelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
    if (TubeList.SelectedItem == null)
       return;

    TubeList.ScrollIntoViewCentered(TubeList.SelectedItem);
}

, SelectedItem . , , :

private void OnSelectedItemChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
    if (TubeList.SelectedItem == null)
       return;

    var container = TubeList.ItemContainerGenerator.ContainerFromItem(TubeList.SelectedItem) as FrameworkElement;

    if(!container.IsVisible)
       TubeList.ScrollIntoViewCentered(TubeList.SelectedItem);
}

SelectedItem , null. . , ItemsSource , SelectedItem, , SelectedItem . .

, , - . - ? , .

.

+5
3

, , ItemContainerGenerators ... ( TreeView)

UpdateLayout(), ItemContainerGenerators.

+5

, , , . , , .

+3

- - , ? Linq - .

, SelectedTube Items [0].

+1

All Articles