如何禁用wpf中的按钮
How to disable button in wpf
我使用 IsEnabled 的 属性 将我的按钮绑定到我的 ViewModel 中,以便从我的 ViewModel 中设置为 true 或 false,但它不会在我将 属性 设置为 false 时禁用它.
我的XAML
<Button x:Name="buttonSubmit" Margin="20,10,0,0" Height="30" Width="90" Content="Login" IsEnabled="{Binding IsLoginEnabled, Mode=TwoWay}" Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=txtPassword}"/>
视图模型
public LoginViewModel(ILoginAuth loginAuth)
{
this.IsLoginEnabled = true;
this.LoginCommand = new DelegateCommand(this.LoginUser);
}
public async void LoginUser()
{
this.IsLoginEnabled = false;
}
我的第一个猜测是您没有在 ViewModel 中实现 INotifyPropertyChanged。
查看这些链接:
Explain INotifyPropertyChanged In WPF - MVVM
How to: Implement the INotifyPropertyChanged Interface
您需要实现该接口,以便 ViewModel 通知视图某些内容已更改并相应地更新 UI。
当您还绑定了 Command
属性 时,您通常不会绑定 IsEnabled
。 ICommand对象的CanExecute
方法控制Button是否启用:
public DelegateCommand LoginCommand { get; }
private bool canLogin = true;
public LoginViewModel(ILoginAuth loginAuth)
{
LoginCommand = new DelegateCommand(LoginUser, () => canLogin);
}
public void LoginUser()
{
canLogin = false;
LoginCommand.RaiseCanExecuteChanged();
}
我使用 IsEnabled 的 属性 将我的按钮绑定到我的 ViewModel 中,以便从我的 ViewModel 中设置为 true 或 false,但它不会在我将 属性 设置为 false 时禁用它.
我的XAML
<Button x:Name="buttonSubmit" Margin="20,10,0,0" Height="30" Width="90" Content="Login" IsEnabled="{Binding IsLoginEnabled, Mode=TwoWay}" Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=txtPassword}"/>
视图模型
public LoginViewModel(ILoginAuth loginAuth)
{
this.IsLoginEnabled = true;
this.LoginCommand = new DelegateCommand(this.LoginUser);
}
public async void LoginUser()
{
this.IsLoginEnabled = false;
}
我的第一个猜测是您没有在 ViewModel 中实现 INotifyPropertyChanged。
查看这些链接:
Explain INotifyPropertyChanged In WPF - MVVM
How to: Implement the INotifyPropertyChanged Interface
您需要实现该接口,以便 ViewModel 通知视图某些内容已更改并相应地更新 UI。
当您还绑定了 Command
属性 时,您通常不会绑定 IsEnabled
。 ICommand对象的CanExecute
方法控制Button是否启用:
public DelegateCommand LoginCommand { get; }
private bool canLogin = true;
public LoginViewModel(ILoginAuth loginAuth)
{
LoginCommand = new DelegateCommand(LoginUser, () => canLogin);
}
public void LoginUser()
{
canLogin = false;
LoginCommand.RaiseCanExecuteChanged();
}