带参数的 ICommand 接口不起作用

ICommand Interface with Parameters doesn´t work

我正在尝试使用 ICommand-Data 绑定。因此我制作了一个应该像这样工作的应用程序: 我有 2 个按钮。一个是“+1”,它只是向上计数。第二个是 "Multipy",它应该将值乘以自身。例如:我点击第一个按钮 3 次。现在我按下第二个按钮:它生成 3*3,我们得到 9 作为新值。第一个按钮在工作,我想第二个按钮也没有那么糟糕,但是我不能在执行时给它参数。看看:

public class CounterViewModel : BaseViewModel
{

    public ObservableCollection<NumberViewModel> Nummer { get; private set; } = new ObservableCollection<NumberViewModel>();
    int current = 0;

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

    Number Zahl = new Number();

    public CounterViewModel()
    {
        CountUpCommand = new Command(CountUp);
        DelCommand = new Command(SetZero);
        //MultiplyCommand = new Command<int>(Multiply).Execute(current); 
        //MultiplyCommand = new Command<int>(current => Multiply(current));
        // Both doesen´t work
    }


    public void CountUp()
    {
        // current = Nummer.Count + 1;
        current = current + 1;
        Nummer.Add(new NumberViewModel { Num = current });
    }

    public void Multiply(int _multiply)
    {
        current = _multiply * _multiply;
        Nummer.Add(new NumberViewModel { Num = current });
    }

还有我的 "Number.cs":

public class Number
{

    public int Num { get; set;}

} 

对于感兴趣的人,我的 xaml 文件:

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

但我不知道这是不是必要的。你能帮帮我吗?

您的命令绑定没有指定任何命令参数,这就是它不起作用的原因。

您需要像这样在 xaml 文件中指定它。

 <Button Text="Erg x Erg" Command="{Binding MultiplyCommand}" CommandParameter="{Binding CurrentNumber}"/>

为此,您还需要使用正确的数字 属性 更新视图模型:

private int _currentNumber;
public int CurrentNumber
{
    get
    {
        return _currentNumber;
    }
    set
    {
        _currentNumber = value;
        OnPropertyChanged(nameof(CurrentNumber));
        // or (depending on if the Method uses the [CallerMemberName] attribute)
        OnPropertyChanged();
    }
}


public void CountUp()
{
    // current = Nummer.Count + 1;
    CurrentNumber += Current + 1;
    Nummer.Add(new NumberViewModel { Num = CurrentNumber });
}

public void Multiply(int multiplyParameter)
{
    CurrentNumber = multiplyParameter * multiplyParameter;
    Nummer.Add(new NumberViewModel { Num = CurrentNumber});
}

RaisePropertyChanged 语法可能会根据您使用的 MVVM 框架而改变,但就是这样。