Home > Net >  Unable to update button based on numbers of elements in a list
Unable to update button based on numbers of elements in a list

Time:02-03

This is a MAUI app.

I have this xaml in MainPage.xaml

<Button                                
  x:Name="SendPhotoBtn"
  Text="Send Photos"
  SemanticProperties.Hint="Send photos to email address"
  Command="{Binding SendPhotoCommand}"
  HorizontalOptions="Center" /> 

And i have an list of items:

[ObservableProperty] 
[NotifyCanExecuteChangedFor(nameof(SendPhotoCommand))] 
ObservableCollection<ImageModel> _items;

And i want the button to be enabled/disabled based on the _items.Count.

I tried having this:

private bool CanSendEmail() 
{    
    return Items.Count > 0;
}

And this command:

[RelayCommand(AllowConcurrentExecutions = false, CanExecute = nameof(CanSendEmail))]
private async Task SendPhotoAsync()
{
  ...
}

It's getting disabled, but never enabled again.

CodePudding user response:

Try to change this method :

private bool CanSendEmail() 
{    
    bool checkItemsCount;

    if(Items.Count > 0)
        checkItemsCount= true;
    else
        checkItemsCount= false;

    return checkItemsCount;
}

And do the job for the button depending on this result.

Or :

private void CanSendEmail() 
{    
    if(Items.Count > 0)
        // SendPhotoBtn is enabled
    else
        // SendPhotoBtn is disabled
}

Hope this helps you.

CodePudding user response:

You could put IsEnabled property after Command property then could use binding.(If you put IsEnable before the Command, then it doesn't work.)

<Button                                
    x:Name="SendPhotoBtn"
    ...

    Command="{Binding SendPhotoCommand}"
    IsEnabled="{Binding IsEnabled}"
/> 

Then in ViewModel, you could bind to IsEnable.

[ObservableProperty]
private bool isEnabled;

As i don't know the whole code, i just give you some suggestions here. You could use CollectionChanged event to detect the add or remove of an item, such like the following:

    public MainPageViewModel()
    {

        ItemCollection.CollectionChanged  = ItemCollection_CollectionChanged;
    }

    private void ItemCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (ItemCollection.Count > 0)
        {
            IsEnabled = true;
        }
        else
        {
            IsEnabled = false;
        }
    }

Hope it works for you.

  • Related