我有 2 个按钮,我想根据计数器禁用/启用
这是我的柜台
private int _stepCounter = 0;
public int StepCounter
{
get { return _stepCounter; }
set{_stepCounter=value; OnPropertyChanged("StepCounter");}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
我写了下面的 IValueConverter
[ValueConversion(typeof(int), typeof(bool))]
class inttobool : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture, string ButtonName)
{
int stepcount = (int)value;
if (stepcount == 0 && ButtonName == "PreviousStepButton")
{
return false;
}
else if (stepcount == 5 && ButtonName == "NextStepButton")
{
return false;
}
else
{
return true;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture, string Buttonname)
{
return null;
}
}
我的按钮看起来像下面这样
<Button Name="NextStepButton" Content="Next Step" Click="NextStepButton_Click" />
<Button Name="PreviousStepButton" Content="PreviousStep"click="PreviousStepButton_Click" />
NextStepButton_Click 事件将计数器加一 PreviousStepButton_Click 事件将计数器减一
我正在尝试学习 mvvm,我的问题是如何将我点击的按钮的名称发送到转换器?
XAML 中 IsEnabled 属性中的绑定(bind)语句应该是什么样的?
我需要在计数器达到 5 时禁用 NextStepButton 当计数器变为 0 时,我需要禁用 PreviousStep 否则两者都已启用。
请您参考如下方法:
i am trying to learn mvvm
MVVM 方法假定,当您想在 View 模型中执行任何操作时,您应该使用命令(任何 ICommand 实现),并将这些命令绑定(bind)到按钮:
<Button Content="Previous" Command="{Binding PreviousCommand}"/>
<Button Content="Next" Command="{Binding NextCommand}"/>
通常,ICommand 实现是 RelayCommand/DelegateCommand(google 一下)。这些实现允许您在 View 模型中定义两个委托(delegate):
- 第一个是命令负载,一个 Action 本身。
- 第二个是检查执行该操作的能力。
WPF 按钮熟悉 ICommand,因此,如果命令绑定(bind)到按钮,按钮调用 CanExecute,如果它返回 false ,按钮将被禁用。
这里不需要转换器(当然,对于任何 button_Click 处理程序)。
您甚至不需要任何 IsNextEnabled/IsPreviousEnabled 属性 - 绑定(bind)和 CanExecute 会为您完成这项工作。
