How to enable button if ListView has a selected item?

dinobdinob USUniversity ✭✭✭
edited October 2018 in Xamarin.Forms

I have a ListView in my Xamarin.Forms project and I want to enable a button only if there is a selected item in the list view. I tried adding DataTrigger for my Button that checks for SelectedItem Value if it is null or not but this does not work

<StackLayout Orientation="Vertical">   
    <ListView x:Name="lvwCars" ItemsSource="{Binding Cars}"
      SelectedItem="{Binding SelectedCar}">
     <ListView.ItemTemplate>
      <DataTemplate>
       <ViewCell>
        <StackLayout Orientation="Horizontal">
         <Label Text="{Binding PlateNumber}" />
         <Label Text="{Binding OwnerName}" />    
        </StackLayout>
       </ViewCell>
      </DataTemplate>
     </ListView.ItemTemplate>
    </ListView>
</StackLayout>

<StackLayout Orientation="Horizontal"> 
    <Button x:Name="btnBack" 
            Text="Back" 
            Command="{Binding BackClickCommand}"/>
    <Button x:Name="btnNext" 
            Text="Next" 
            IsEnabled="False"
            Command="{Binding ConfirmClickCommand}">
     <Button.Triggers>
      <DataTrigger TargetType="Button" 
       Binding="{Binding Source={x:Reference lvwCars}, Path=SelectedItem}" Value="null">
       <Setter Property="IsEnabled" Value="False"/>
      </DataTrigger>
     </Button.Triggers>
    </Button>
</StackLayout>

Answers

  • NMackayNMackay GBInsider, University mod

    Really the viewmodel can take care of this, you can set a condition in the CanExecute of your command to evaluate a boolean state in the viewmodel and the button will disable automatically. Using a trigger and relative source binding won't work, might work on paper....

  • dinobdinob USUniversity ✭✭✭

    @NMackay said:
    Really the viewmodel can take care of this, you can set a condition in the CanExecute of your command to evaluate a boolean state in the viewmodel and the button will disable automatically. Using a trigger and relative source binding won't work, might work on paper....

    Can you provide some code to support this. I know that Command could be used for that. So could be DataTrigger and who know what else. But I am trying to get to some sort of solution that can help me resolve this rather than chat about it.

  • NMackayNMackay GBInsider, University mod

    It's in the documentation! And as I said, a trigger generally isn't the correct approach for this scenario

    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/commanding

    I wasn't chatting, I was trying to help, anyway, good luck.

Sign In or Register to comment.