Search code examples
c#visual-studioxamarinxamarin.formsicommand

How to deactivate button in Xamarin With ICommand


I got an application which has 2 buttons. First is counting up, second says "set 0" in Xamarin forms. I want the upcountButton do get Gray/Disabled when the value of 512 get hit. here my Code:

    public ObservableCollection<NumberViewModel> Nummer { get; private set; } = new ObservableCollection<NumberViewModel>();
    private int _currentNumber;
    public int Current
    {
        get
        {
            return _currentNumber;
        }
        set
        {
            _currentNumber = value;
            OnPropertyChanged();
        }
    }

    public ICommand CountUpCommand { get; private set; }
    public ICommand DelCommand { get; private set; }

    Number Zahl = new Number();

    public CounterViewModel()
    {
        CountUpCommand = new Command(CountUp);
        DelCommand = new Command(SetZero);
    }

    public void SetZero()
    {
        Current = 0;
        Nummer.Add(new NumberViewModel { Num = Current});
        Checker(Current);

    }

    public void CountUp()
    {

            Current++;
            Nummer.Add(new NumberViewModel { Num = Current });
        Checker(current);


    }
    public void Checker(int check)
    {
        if (check > 512)
        {
            //button.grayout
        }
        else { }
    }

So how can i bind this to the enable-status of my button?

Oh, I forgot my xaml code:

<StackLayout>
        <Button Text="+1" Command="{Binding CountUpCommand}" x:Name="plusOne" />
        <Button Text="DEL" Command="{Binding DelCommand}" />
    </StackLayout>
<Label Text="--------------" />
<StackLayout>
    <ListView ItemsSource="{Binding Nummer}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell 
                Text="{Binding Num}"
                x:Name="ElNr"
                />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

Solution

  • Each command has a CanExecute method.

    When you return false from that method, the related button will appear as disabled.

    Just make sure you call the ChangeCanExecute to notify the UI that the command status changed.

    For example:

    public CounterViewModel()
    {
        CountUpCommand = new Command(CountUp, CanCountUp);
    }
    
    public int Current
    {
        get
        {
            return _currentNumber;
        }
        set
        {
            _currentNumber = value;
            OnPropertyChanged();
            CountUpCommand.ChangeCanExecute();
        }
    }
    
    
    public void CountUp()
    {
        Current++; //will result in calling CanCountUp and updating button status
        Nummer.Add(new NumberViewModel { Num = Current });
    }
    
    public bool CanCountUp()
    {
        return Current <= 512;  
    }
    

    P.S. You should use camelcase for public member names, for instance Current instead of current.