Get selecteditem from listbox using MVVM

ε祈祈猫儿з 提交于 2019-12-03 22:15:58
AlexDrenea

I would create a "SelectedCustomer" property in the ViewModel (next to you Customers property) and bind it to the SelectedItem. Then, on the setter of that property you can navigate to your desired page. This way you eliminate the messy events and command.

<ListBox x:Name="state_list 
         ItemsSource="{Binding Customers}" 
         SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}">

...

public Customer SelectedCustomer
{
  get
  {
    return _selectedCustomer;
  }
  set
  {
    if (value != null)
    {
    _selectedCustomer = value;
    //Navigate to your page here, either with Navigator class or any other mechanism you have in place for changing content on screen
    }
  } 

}

AlexDrenea gives you a good way of binding SelectedItem to a property on your viewmodel. If you are wanting to navigate based on this in an MVVM architecture, I would suggest using messaging to get it done.

I cover this in a blog post I did a while back, but the short summary of doing this within MVVMLight, is to create a Navigator class that sits at the application level.

public class Navigator
    {

        private PhoneApplicatoinFrame RootFrame;

        public Navigator(PhoneApplicationFrame frame)
        {
            RootFrame = frame;
            RegisterMessages();
        }

        private void RegisterMessages()
        {
            Messenger.Default.Register<ShowTrackerMessage>(this, ShowTracker);
        }

        private void ShowTracker(ShowTrackerMessage msg)
        {
            RootFrame.Navigate(new Uri("/Views/ItemLocationCompassView.xaml", UriKind.RelativeOrAbsolute));
        }

}

Then, as part of your application start-up, create it and pass it a reference to your RootFrame:

    private static Navigator _navigator;
    public static Navigator Nav
    {
        get { return _navigator; }
    }

...

_navigator = new Navigator(this.RootFrame);

Then, you have a couple choices on how you send the Navigation message.

Option 1: In your ViewModel, hook into the PropertyChanged event (part of INotifyPropertyChanged), and send the appropriate message when your SelectedItem property changes.

Option 2: Tie into the SelectionChanged event of your ListBox. I use the MVVMLight's EventToCommand to send that event to a RelayCommand in my ViewModel, then react appropriately to send the message to the Navigator object.

I cover this in more detail at: http://www.smartchitecture.com/?p=27

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!