我想在我的自定义控件中添加一个方法,我可以使用命令绑定在我的MainWindow.xaml中调用一个按钮。我在网上遇到了一些解决方案,但其中一个解决方案看起来没有工作,另一个解决了。有人能向我解释设置这个的正确方法吗?第一种解决方案如下所述产生错误。第二种解决方案有效,但我不确定任何优点/缺点。向按钮绑定的自定义控件添加命令wpf
溶液1 - 碎
public partial class MyControl : Control
{
...
public static readonly RoutedCommand AlignLeftCommand = null;
static MyControl()
{
binding = new CommandBinding();
binding.Command = AlignLeftCommand;
binding.Executed += new ExecutedRoutedEventHandler(AlignLeft_Executed);
CommandManager.RegisterClassCommandBinding(typeof(MyControl), binding);
}
}
错误:
Severity Code Description Project File Line Error CS0120 An object reference is required for the non-static field, method, or property...
溶液2
public partial class MyControl : Control
{
...
public static readonly RoutedCommand AlignLeftCommand = new RoutedCommand();
public MyControl()
{
this.CommandBindings.Add(new CommandBinding(MyControl.AlignLeftCommand, AlignLeft_Executed, null));
}
}
下面是按钮调用该方法。
<StackPanel Orientation="Horizontal">
<Button Content="Left Edges" FontSize="8"
Command="{x:Static JM:MyControl.AlignLeftCommand}"
CommandTarget="{Binding ElementName=mycontrol}"/>
</StackPanel>
是您的应用程序MVVM或代码隐藏? – StepUp