将命令添加到按钮绑定wpf的自定义控件

时间:2016-02-04 14:01:26

标签: c# wpf

我想在我的MainWindow.xaml中为我的自定义控件添加一个方法,我可以使用命令绑定从一个按钮调用该方法。我在网上遇到过一些解决方案,但其中一个似乎没有用,另一个没有。有人可以向我解释设置它的正确方法。第一种解决方案产生和错误,如下所述。第二个解决方案有效,但我不确定任何优点/缺点。

解决方案1 ​​ - 已损坏

for %%s in (%ToBeUninstalled%) do (
REG QUERY "%KEY64%\%%s" | find /i "UninstallString" > NUL && (msiexec.exe /x %%s /qb) || (echo Software not installed)
)

错误:

  

严重级代码说明项目文件行   错误CS0120非静态字段,方法或属性需要对象引用...

解决方案2

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

这是调用方法的按钮。

public partial class MyControl : Control
{
    ...
    public static readonly RoutedCommand AlignLeftCommand = new RoutedCommand();

    public MyControl()
    {
        this.CommandBindings.Add(new CommandBinding(MyControl.AlignLeftCommand, AlignLeft_Executed, null));
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您应该在Window上定义命令绑定(为ExecutedCanExecute事件创建处理程序):

<Window x:Class="CommandBindingWPF.MainWindow"
        ...The code omitted for the brevity...
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.New" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute" />
    </Window.CommandBindings>

并声明您的Button ix xaml:

<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
    <Button Command="ApplicationCommands.New">New</Button>
</StackPanel>

在命令绑定创建后,应在代码隐藏中创建处理程序:

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
   MessageBox.Show("Hello from Command");
}

private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{      }

<强>更新

对于MVVM应用程序:

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

然后在viewModel中创建一个属性。例如:

public class YourViewModel
{
    public RelayCommand YourCommand { get; set; }
    public YourViewModel()
    {
        YourCommand = new RelayCommand(DoSmth, CanDoSmth);
    }

    private void DoSmth(object obj)
    {
        Message.Box("Hello from viewModel"); 
    }

    private bool CanDoSmth(object obj)
    {
       //you could implement your logic here. But by default it should be  
       //set to true
       return true;
    }
}

XAML应该看起来像:

<Button Content="Click me!" Command="{Binding YourCommand}"/> 

为了熟悉MVVM,我建议你阅读Rachel Lim的博客。她有能力教人,她可以用简单的术语来解释。 Read Rachel Lim's blog. 熟悉MVVM命令see that post