开发者

How to set the selected item on a listbox after binding using MVVM Light?

开发者 https://www.devze.com 2023-01-06 20:31 出处:网络
I\'m using MVVM Light on an Windows Phone app.I would like to set the selected item on a listbox after it is databound.

I'm using MVVM Light on an Windows Phone app. I would like to set the selected item on a listbox after it is databound.

I thought the best way to do this is to setup an eventToCommand on the listbox for the Loaded event and pass the element to set the selected index, but I'm no开发者_StackOverflowt sure how I can pass the listbox element to the RelayCommand.


Think about this from the perspective of your viewmodel not in terms of the controls in your view...

Bind the SelectedItem property of the listbox to a new MySelectedItem property on your viewmodel and then you can do it all in the viewmodel without any commands.

For instance you might iterate through the collection of items in your viewmodel that are bound to the ItemsSource of you listbox and then assign one of them to your new MySelectedItem property, and automagically it will show up as selected in the UI.

As an an alternative you can also bind the IsSelected property of EVERY ListBoxItem to a new MyIsSelected property on each object in the collection. Same end result... use whichever approach suits you situation and/or taste...

0

精彩评论

暂无评论...
验证码 换一张
取 消