我正在尝试通过ICommand-Data Binding来取暖。为此,我制作了一个应如下工作的应用程序: 我有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>
但是我不知道这是否是nesecerry。你能帮我吗?
答案 0 :(得分:1)
您的命令绑定没有指定任何命令参数,这就是为什么它不起作用的原因。
您需要像这样在xaml文件中指定它。
<Button Text="Erg x Erg" Command="{Binding MultiplyCommand}" CommandParameter="{Binding CurrentNumber}"/>
为此,您还需要使用正确的Number属性更新viewmodel:
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框架而变化,但这就是想法。