你如何执行Silverlight ICommand?

时间:2011-08-24 05:13:45

标签: silverlight-4.0 silverlight-3.0 command routed-commands icommand

这是一个基本问题,但我不得不问。

在SL中,我有这个XAML:

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

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

这个代码背后:

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();
    }
}

但是当我点击按钮时,Command的Execute()永远不会被触发。

有诀窍吗?

1 个答案:

答案 0 :(得分:0)

没有技巧,你的问题在于你的XAML和C#类之间的绑定。您不能仅将字段绑定到属性。

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());
        }
    }
}