[英]WPF ListBox send SelectedItem value to the viewmodel
Inside MainWindow there is listbox filled with some data. 在MainWindow里面有一个填充了一些数据的列表框。 These data is loaded from viewmodel, so I dont have any codebehind. 这些数据是从viewmodel加载的,所以我没有任何代码隐藏。
MainWindow.xaml 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? 如何知道在列表框中选择哪本书(使用ICommand
)并将其属性(例如int Id
)发送到viewmodel
以进行进一步处理?
Simply bind SelectedItem
to some property (say SelectedBook ) in your ViewModel, no need to have ICommand for this. 只需将SelectedItem
绑定到ViewModel中的某个属性(比如SelectedBook ),就不需要为此提供ICommand 。
<ListBox Name="listBoxData"
ItemTemplate="{DynamicResource BookTemplate}"
ItemsSource="{Binding Books}"
SelectedItem="{Binding SelectedBook}" />
You can get Id for the book by simply accessing ViewModel property: 只需访问ViewModel属性,您就可以获得该书的ID:
int selectedBookId = SelectedBook.Id;
Add a SelectedBook
property to your ViewModel
class, preferably of your Book
type. 将SelectedBook
属性添加到ViewModel
类,最好是Book
类型。
Then in your XAML, add the proper Binding
: 然后在你的XAML中,添加适当的Binding
:
<ListBox SelectedItem="{Binding SelectedBook}"/>
If it acts up, you can force it to be a TwoWay
binding, like so: 如果它起作用,你可以强制它成为TwoWay
绑定,如下所示:
<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. 您的SelectedBook
属性必须调用正确的PropertyChanged
通知,以便绑定使UI和ViewModel
保持同步。
Rohit is right 罗希特是对的
bind the selected item of the listbox to a property that is in the viewmodel: 将列表框的选定项绑定到viewmodel中的属性:
like this: (using a property called SelectedBook) 像这样:(使用名为SelectedBook的属性)
<ListBox Name="listBoxData"
DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}"
SelectedItem="{Binding Path=SelectedBook, Mode=TwoWay}"
ItemTemplate="{DynamicResource BookTemplate}"
ItemsSource="{Binding Books}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.