如何使用WPF(后端)

时间:2016-02-18 15:11:01

标签: wpf command controls

如何在WPF中向按钮控件添加命令,后端有代码?

1 个答案:

答案 0 :(得分:2)

在代码隐藏中添加命令的简单示例

class SomeCommand : ICommand
{
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        MessageBox.Show("From command");
    }
}

在InitializeComponent();

之后的构造函数中
        var btnCompare = new Button();
        btnCompare.Content = "Compare";
        btnCompare.Command = new SomeCommand();

        grid.Children.Add(btnCompare);

<强>更新

正如我从你的评论中所理解的那样,你想将一个参数传递给command,它应该根据某些条件改变ICommand.CanExecute方法的返回值。可以通过将委托作为参数传递并在命令中实现CanExecuteChanged事件作为CommandManager.RequerySuggested事件的包装来实现。命令应该触发CanExecuteChanged来通知框架,改变CanExecute方法的返回值。

通常,每当用户与应用程序的界面交互时,就会触发CommandManager.RequerySuggested,对于其他情况,您可以调用CommandManager.InvalidateRequerySuggested()静态方法。 以下是用于说明该方法的代码。

<强> XAML

<Grid Name="grid">
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <CheckBox Content="Bool value is true" Click="checkBoxBool_Click" IsChecked="True"/>
</Grid>

<强> C#

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

    public bool CanExecute(object parameter)
    {
        Func<bool> isTrue = (Func<bool>)parameter;
        return isTrue != null && isTrue();
    }

    public void Execute(object parameter)
    {
        MessageBox.Show("From command");
    }
}

...

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var btnCompare = new Button();
        btnCompare.Content = "Compare";

        btnCompare.CommandParameter = new Func<bool> (() => GetBoolValue());
        btnCompare.Command = new SomeCommand();

        btnCompare.SetValue(Grid.RowProperty, 1);

        grid.Children.Add(btnCompare);
    }

    private bool _boolValue = true;
    private bool GetBoolValue()
    {
        return _boolValue;
    }

    private void checkBoxBool_Click(object sender, RoutedEventArgs e)
    {
        _boolValue = (e.Source as CheckBox).IsChecked == true;

    }
}