簡體   English   中英

向自定義控件添加命令以進行按鈕綁定WPF

[英]adding commands to custom control for button binding wpf

我想在自定義控件中添加一個方法,可以在MainWindow.xaml中使用命令綁定從按鈕調用該方法。 我在網上遇到了一些解決方案,但是其中一個似乎沒有用,而另一個則可以。 有人可以向我解釋設置此方法的正確方法。 第一個解決方案產生並產生錯誤,如下所述。 第二種解決方案有效,但是我不確定任何利弊。

解決方案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);
    }
}

錯誤:

嚴重性代碼說明項目文件行錯誤CS0120非靜態字段,方法或屬性需要對象引用。

解決方案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>

首先,您應該像這樣在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的博客。 她有教人的才能,可以用簡單的術語來解釋。 閱讀Rachel Lim的博客。 要了解MVVM命令, 請參閱該文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM