Command not firing when setting type

robiharidrobiharid Member ✭✭
edited August 14 in General

XAML:
<ListView x:Name="VisitorListView" ItemsSource="{Binding FilteredVisitors}" SelectedItem="{Binding SelectedVisitor}"> <ListView.Behaviors> <behaviors:EventToCommandBehavior EventName="ItemSelected" Command="{Binding VisitorSelectedCommand}" Converter="{StaticResource SelectedVisitorConverter}"/> </ListView.Behaviors> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label WidthRequest="600" Text="{Binding Name}" /> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>

ViewModel:
public ICommand VisitorSelectedCommand { get; private set; }
(Constructor)
VisitorSelectedCommand = new Command<Visitor>(SelectedItemChanged);
(Command method)
private void SelectedItemChanged(Visitor visitor) { try { SearchText = visitor.Name; } catch (Exception e) { Console.WriteLine(e); throw; } }

The method does not get called in the VM constructor. SelectedItemChanged does not enter.

Debugging through the EventToCommandBehaviour (provided by the Xamarin docs)
if (Command.CanExecute(resolvedParameter)) { Command.Execute(resolvedParameter); }

My command.execute is called but I cannot step into it, it just steps over the exit brace. My working commands are new Command(methodName) and work without the typecast to .

I need the typecast because I want to bind the SelectedItem from the ListView. and I keep hitting race conditions, so using a converter would mean I am able to pass both the SelectedItem and the Event to the VM.

Answers

  • Sandman9Sandman9 Member ✭✭

    It's not a command but it's works fine for find selectedItem in your list. And already have a type :) You can try this.

    ListView:

    ViewModel:

    private YourModel _selectedItem;

    public YourModel SelectedItem
    {
    get
    {
    return _selectedItem;
    }
    set
    {
    SetValue(ref _selectedItem, value);
    OnPropertyChanged(nameof(_selectedItem));
    GetSelectedItem(_selectedItem);
    }
    }

    private async void GetSelectedItem(YourModel model)
    {
    //You can do here what do you want :)
    }

    By the way, maybe you want to know. I gave my ViewModel to my Page's BindingContext.

Sign In or Register to comment.