gpt4 book ai didi

c# - 满足条件时 CanExecute() 不启用按钮

转载 作者:太空狗 更新时间:2023-10-30 00:07:25 30 4
gpt4 key购买 nike

我有一个非常简单的应用程序,其中包含一个 TextBox 和一个 Button。当输入到 TextBox 中的文本长度超过 5 个字符时,该按钮将被启用。这是我的 ViewModel 的代码:

private string _text { get; set; }
public string Text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged("Text");
}
}

private ICommand _buttonCommand;
public ICommand ButtonCommand
{
get
{
if (_buttonCommand == null)
{
_buttonCommand = new RelayCommand(
param => this.ButtonCommandExecute(),
param => this.ButtonCommandCanExecute()
);
}
return _buttonCommand;
}
}

private bool ButtonCommandCanExecute()
{
if (this.Text.Length < 5)
{
return false;
}
else
{
return true;
}
}

private void ButtonCommandExecute()
{
this.Text = "Text changed";
}

public MainWindowViewModel()
{
//
}

TextBoxButton 使用此 XAML 绑定(bind):

<Button Content="Button" HorizontalAlignment="Left" 
Margin="185,132,0,0" VerticalAlignment="Top" Width="120"
Command="{Binding Path=ButtonCommand}" />

<TextBox HorizontalAlignment="Left" Height="23"
Margin="185,109,0,0" TextWrapping="Wrap"
Text="{Binding Path=Text, Mode=TwoWay}" VerticalAlignment="Top" Width="120"/>

DataContext 似乎设置正确,但这只是因为我是 WPF 初学者:

private MainWindowViewModel view_model;

public MainWindow()
{
InitializeComponent();

view_model = new MainWindowViewModel();

this.DataContext = view_model;
}

当我输入 TextBox 时,Button 永远不会启用。

最佳答案

ICommand 接口(interface)的一些实现有特殊的方法来通知“CanExecute”是否已经改变。 RelayCommand 类(MVVM Light)有这样的方法。

private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged("Text");

// There is a special RelayCommand method to notify "CanExecute" changed.
// After this call, the "CanExecute" state is "re-evaluated" automatically by binding using CanExecute Func passed into RelayCommand constructor.
_buttonCommand.RaiseCanExecuteChanged();
}
}

private RelayCommand _buttonCommand;
public ICommand ButtonCommand
{
get
{
if (_buttonCommand == null)
{
_buttonCommand = new RelayCommand(
param => this.ButtonCommandExecute(),
param => this.ButtonCommandCanExecute()
);
}
return _buttonCommand;
}
}

这个问题很有用:What is CanExecuteChanged for?

关于c# - 满足条件时 CanExecute() 不启用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828572/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com