在代码中将IsEnabled属性绑定到一个变量,而不是直接绑定到属性。这样,我们就可以在代码中控制按钮是否可用。以下是示例代码:
在XAML中绑定IsEnabled属性:
在代码中定义变量并控制按钮是否可用:
public class MyViewModel : INotifyPropertyChanged { private bool _isButtonEnabled; public bool IsButtonEnabled { get { return _isButtonEnabled; } set { _isButtonEnabled = value; OnPropertyChanged("IsButtonEnabled"); } }
//Constructor
public MyViewModel()
{
//按钮一开始是可用的
IsButtonEnabled = true;
//在这里将按钮禁用
IsButtonEnabled = false;
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}