I have a very simple application with a TextBox
and a Button
. When the text entered into the TextBox
exceeds 5 characters in length, the button will be enabled. Here is the code for my 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()
{
//
}
The TextBox
and Button
are bound using this 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"/>
The DataContext
appears to be set correctly, but here it is just because I am a WPF beginner:
private MainWindowViewModel view_model;
public MainWindow()
{
InitializeComponent();
view_model = new MainWindowViewModel();
this.DataContext = view_model;
}
When I type into the TextBox
, the Button
never enables.