这是一个基本问题,但我不得不问。
在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()永远不会被触发。
有诀窍吗?
答案 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());
}
}
}