use*_*858 4 c# wpf relaycommand
我有一个非常简单的应用程序与a TextBox和a 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()
{
//
}
Run Code Online (Sandbox Code Playgroud)
该TextBox和Button使用此XAML约束:
<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"/>
Run Code Online (Sandbox Code Playgroud)
在DataContext似乎是正确设置,但在这里它仅仅是因为我是一个WPF初学者:
private MainWindowViewModel view_model;
public MainWindow()
{
InitializeComponent();
view_model = new MainWindowViewModel();
this.DataContext = view_model;
}
Run Code Online (Sandbox Code Playgroud)
当我输入时TextBox,Button永远不会启用.
Ser*_*nov 14
ICommand接口的某些实现具有特殊方法来通知"CanExecute"是否已更改.RelayCommandclass(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;
}
}
Run Code Online (Sandbox Code Playgroud)
这个问题很有用:什么是CanExecuteChanged?