我有一个非常简单的应用程序,其中包括一个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()
{
//
}
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"/>
DataContext
看起来已经正确设置了,但这只是因为我是一个 WPF 的初学者。
private MainWindowViewModel view_model;
public MainWindow()
{
InitializeComponent();
view_model = new MainWindowViewModel();
this.DataContext = view_model;
}
当我在
TextBox
中输入时,Button
从未启用。