如何使用ICommand停用Xamarin中的按钮

时间:2018-10-15 11:30:02

标签: c# visual-studio xamarin xamarin.forms icommand

我有一个具有2个按钮的应用程序。首先是递增计数,其次以Xamarin形式说“ set 0”。我希望当值512被命中时,upcountButton会变成灰色/禁用。 这是我的代码:

    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 { }
    }

那么如何将其绑定到按钮的启用状态?

哦,我忘记了我的xaml代码:

<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>

1 个答案:

答案 0 :(得分:2)

每个命令都有一个CanExecute方法。

从该方法返回false时,相关按钮将显示为已禁用。

只需确保调用ChangeCanExecute来通知UI命令状态已更改。

例如:

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。您应使用驼峰式表示法作为公共成员名称,例如Current而不是current