我有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属性中的绑定语句应该是什么样的?
我需要在计数器达到5时禁用NextStepButton
我需要在计数器变为0时禁用PreviousStep
其他方面都已启用。
答案 0 :(得分:3)
我正在尝试学习mvvm
MVVM方法假设您应该使用命令(任何ICommand
实现),当您想在视图模型中执行任何操作,并将这些命令绑定到按钮时:
<Button Content="Previous" Command="{Binding PreviousCommand}"/>
<Button Content="Next" Command="{Binding NextCommand}"/>
通常,ICommand
实施是RelayCommand
/ DelegateCommand
(google it)。这些实现允许您在视图模型中定义两个委托:
WPF按钮熟悉ICommand
,因此,如果命令绑定到按钮,则按钮调用CanExecute
,如果它返回false
,则该按钮将被禁用。
这里不需要转换器(当然,对于任何button_Click
处理程序)
您甚至不需要任何IsNextEnabled
/ IsPreviousEnabled
属性 - 绑定和CanExecute
为您执行此操作。
答案 1 :(得分:1)
以下是使用MVVM执行此操作的代码。
查看:
<Button Content="Next Step Button" IsEnabled="{Binding NextStepButtonEnabled}" Command="{Binding NextStepButtonCommand}" />
<Button Content="Previous Step Button" IsEnabled="{Binding PreviousStepButtonEnabled}" Command="{Binding PreviousStepButtonCommand}" />
视图模型
// Binding Command.
private ICommand _nextStepButtonCommand;
public ICommand NextStepButtonCommand
{
get { return _nextStepButtonCommand?? (_nextStepButtonCommand= new RelayCommand(NextStepButton);}
}
// Button Action
public void NextStepButton()
{
_stepCounter++;
}
// Button enabled check,
public bool NextStepButtonEnabled { get { return _stepCounter == 5 ? false : true; } }
private ICommand _previousStepButtonCommand;
public ICommand PreviousStepButtonCommand
{
get { return _previousStepButtonCommand?? (_previousStepButtonCommand= new RelayCommand(PerviousStepButton);}
}
public void PerviousStepButton()
{
_stepCounter--;
}
public bool PreviousStepButtonEnabled { get { return _stepCounter == 0 ? false : true; } }