Window.xaml
<window x:class="CPTest.Window1" xmlns:x="#unknown">
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="225">
<grid>
<textbox text="{Binding Path=Content, UpdateSourceTrigger=PropertyChanged}" height="23" horizontalalignment="Left" margin="68,28,0,0" name="textBox1" verticalalignment="Top" width="120" acceptsreturn="False" />
<button command="{Binding Path=Click}" content="Button" height="23" horizontalalignment="Left" margin="80,72,0,0" name="button1" verticalalignment="Top" width="75" />
</grid>
</window>
Window.cs
namespace CPTest
{
public partial class Window1 : Window
{
internal Presenter myPresenter = new Presenter();
public Window1()
{
InitializeComponent();
DataContext = myPresenter;
}
}
}
Presenter.cs
namespace CPTest
{
class Presenter : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private string _Content;
public string Content
{
get { return _Content; }
set
{
_Content = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Content"));
}
}
}
public ICommand Click { get; private set; }
public Presenter()
{
Click = new DelegateCommand(ExecuteTest, CanExecuteTest);
}
public void ExecuteTest(object obj)
{
}
public bool CanExecuteTest(object obj)
{
return !string.IsNullOrEmpty(Content);
}
}
}
If your CanExecuteTest is not getting called over and over then I suspect there is something wrong with your DelegateCommand class code.
My code for DelegateCommand is included here for completeness.
class DelegateCommand : ICommand
{
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public void Execute(object parameter)
{
_execute(parameter);
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}