I am try to Binding a ICommand property on a Button Command from MainWindow. But it`s not working.
Here is sample code which I try for this.
C# Code :
public partial class MainWindow : Window
{
private ICommand _StartButtonCommand;
public ICommand StartButtonCommand
{
get{ return this._StartButtonCommand;}
set
{
if (this._StartButtonCommand!=value)
{
this._StartButtonCommand = value;
}
}
}
public MainWindow()
{
InitializeComponent();
this.StartButtonCommand = new ReplayCommand(new Action<object>(startButtonCommandEx));
}
private void startButtonCommandEx(object obj)
{
MessageBox.Show("Done");
}
protected class ReplayCommand : ICommand
{
private Action<object> _action;
public ReplayCommand(Action<object> action)
{
this._action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
try
{
if (parameter!=null)
{
this._action(parameter);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "AutoShutdown", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
XAML :
<Button x:Name="buttonStrat" Content="Start" HorizontalAlignment="Left" Width="84.274" Height="39.246" Command="{Binding StartButtonCommand, ElementName=window}"/>
Actually I want to access UI Elements Like DataGridView SelectedItem Property or any other UI property using ICommand thats why i am writing ICommand in MainWindow Class.t know this is right way or wrong way. I just try it and i am not success. If it is wrong way please advice me what is right way and how to do it.
I don
Thank`s for advice.
First, you didn’t set the
DataContexton the button:And in the xaml use this:
Also to make your code shorter you could change your property to this: