ItemSelected in View Model

ChrisgozdChrisgozd USMember ✭✭

I have two pages. The view, which is (Menu.xaml and Menu.xaml.cs). The view model which is MenuViewModel.cs.

First I set the bindingcontext in Menu.xaml.cs to MenuViewModel.cs. I am now able to bind properties in xaml to properties in MenuViewModel.

I am trying to bind the ItemSelected event in xaml to a method on MenuViewModel.cs like this :

<ListView x:Name="listView" IsVisible="true" ItemsSource="{Binding NavigationList}" ItemSelected="OnItemSelected" BackgroundColor="White">

But it errors out telling me that it cant find a method "OnItemSelected" on Menu.xaml.cs. Which obviously means I have not bound the event to my MenuViewModel. But how do I do this in xaml?

ItemSelected="{Binding Method}"

doesn't work..

Posts

  • StephaneDelcroixStephaneDelcroix USInsider, Beta ✭✭✭✭
    ItemSelected="OnItemSelected"
    

    looks for an event handler in your code behind partial class, not in the view model.

    you can't bind to ItemSelected, but you can bind to SelectedItem bindable property, and get what you expect.

  • rmarinhormarinho PTMember, Insider, Beta Xamurai

    Try something like this:

    <ListView x:Name="lstCategories" ItemsSource="{Binding Categories}" SelectedItem="{Binding SelectedCategory, Mode=TwoWay}">

    and your view model:

    private ObservableCollection<TipCategory> _categories;
            public ObservableCollection<TipCategory> Categories {
                get{ return _categories;}
                set {
                    _categories = value;
                    RaisePropertyChanged ("Categories");
                }
            }
    
            private TipCategory _selectedCategory;
            public TipCategory SelectedCategory {
                get{ return _selectedCategory;}
                 set {
                    if (value == _selectedCategory)
                        return;
                    _selectedCategory = value;
                    RaisePropertyChanged ("SelectedCategory");
                    UpdateItems ();
                    App.Navigate(new CategoryPage ());
                }
            }
    
Sign In or Register to comment.