Frage

This is such a basic question, but I have to ask.

In SL, I have this XAML:

<UserControl.Resources>
    <local:Commands x:Key="MyCommands" />
</UserControl.Resources>

<Button Content="Click Me" 
        Command="{Binding Path=Click, Source={StaticResource MyCommands}}"
        CommandParameter="Hello World" />

And this code behind:

public class Commands
{
    public ClickCommand Click = new ClickCommand();
    public sealed class ClickCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public void Execute(object parameter)
        {
            MessageBox.Show(parameter.ToString());
        }
    }
}

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }
}

But when I click the button, the Command's Execute() is never fired.

Is there a trick to it?

War es hilfreich?

Lösung

There's no trick, your problem lies in the binding between your XAML and C# class. You can't bind to a field only to a property.

public class Commands
{
    public ClickCommand Click { get; set; }

    public Commands()
    {
        Click = new ClickCommand();
    }

    public sealed class ClickCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            MessageBox.Show(parameter.ToString());
        }
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top