简体   繁体   中英

WPF ListBox send SelectedItem value to the viewmodel

Inside MainWindow there is listbox filled with some data. These data is loaded from viewmodel, so I dont have any codebehind.

MainWindow.xaml

<ListBox Name="listBoxData" 
         DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}" 
         ItemTemplate="{DynamicResource BookTemplate}"                              
         ItemsSource="{Binding Books}" />

How can I know which book is selected inside listbox (using ICommand ) and send it's property ( int Id for example) to viewmodel for further processing?

Simply bind SelectedItem to some property (say SelectedBook ) in your ViewModel, no need to have ICommand for this.

<ListBox Name="listBoxData" 
         ItemTemplate="{DynamicResource BookTemplate}"  
         ItemsSource="{Binding Books}"
         SelectedItem="{Binding SelectedBook}" />

You can get Id for the book by simply accessing ViewModel property:

int selectedBookId = SelectedBook.Id;

Add a SelectedBook property to your ViewModel class, preferably of your Book type.

Then in your XAML, add the proper Binding :

<ListBox SelectedItem="{Binding SelectedBook}"/>

If it acts up, you can force it to be a TwoWay binding, like so:

<ListBox SelectedItem="{Binding SelectedBook, Mode=TwoWay}"/>

It is imperative that your SelectedBook property also invoke the proper PropertyChanged notification so the binding keeps the UI and ViewModel in sync.

Rohit is right

bind the selected item of the listbox to a property that is in the viewmodel:

like this: (using a property called SelectedBook)

 <ListBox Name="listBoxData" 
     DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}" 
     SelectedItem="{Binding Path=SelectedBook, Mode=TwoWay}"
     ItemTemplate="{DynamicResource BookTemplate}"                              
     ItemsSource="{Binding Books}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM