ListBox SelectedItem does not work in MVVM

361 views Asked by At

Hello I have strage issue with SelectedItem property of ListBox. It just does not work.

Here is my code:

XAML:

    <TabControl HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top" ItemsSource="{Binding WszystkieFilmy}" >
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Key}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <ListBox HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="750" ItemsSource="{Binding Value.Filmy}" SelectedItem="{Binding Path=WybranyFilm, Mode=TwoWay}"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

ViewModel:

    public Film WybranyFilm
    {
        get { return zaznaczonyFilm; }
        set
        {
            if (value != zaznaczonyFilm)
            {
                zaznaczonyFilm = value;
                OnPropertyChanged("WybranyFilm");
            }
        }
    }
    public Dictionary<String, ListaFilmow> WszystkieFilmy
    {
        get { return wszystkieFilmy; }
        set
        {
            if (wszystkieFilmy == value)
            {
                return;
            }
            wszystkieFilmy = value;
            OnPropertyChanged("WszystkieFilmy");
        }
    }

And "Value.Filmy" is: ObservableCollection When I select any of item in ListBox it is not assign to "WybranyFilm" variable. I have no idea what is the reason. I have used almost the same solution in other view and it works perfectly. The only difference is that I have ListBox alone there, it is not a part of TabControl.

2

There are 2 answers

2
d.moncada On BEST ANSWER

Looks like the DataContext is incorrect for SelectedItem.

<TabControl x:Name="TabControl" HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top" ItemsSource="{Binding WszystkieFilmy}" >
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Key}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <ListBox HorizontalAlignment="Left" Height="500" VerticalAlignment="Top" Width="750" ItemsSource="{Binding Value.Filmy}" SelectedItem="{Binding ElementName=TabControl, Path=WybranyFilm, Mode=TwoWay}"/>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>
0
Alexandre Severino On

Simply write:

SelectedItem="{Binding WybranyFilm}"

Make sure your Model is set as View's DataContext.