「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.03.18
XML
カテゴリ: C#.NET


CommandManager クラスは、コマンドの処理状態を管理し、再評価するための機能を提供します。以下は、C# WPF アプリケーションで CommandManager を使用するサンプルコードです。


まず、MainWindow.xaml ファイルにボタンを追加します。


```xml

<Window x:Class="CommandManagerExample.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="CommandManager Example" Height="150" Width="300">

    <Grid>

        <Button Content="Execute Command" Command="{Binding ExecuteCommand}"/>

    </Grid>

</Window>

```


次に、MainWindow.xaml.cs ファイルで ViewModel を作成し、CommandManager を使用してコマンドを実行する方法を示します。


```csharp

using System;

using System.Windows;

using System.Windows.Input;


namespace CommandManagerExample

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            DataContext = new MainViewModel();

        }

    }


    public class MainViewModel

    {

        public ICommand ExecuteCommand { get; }


        public MainViewModel()

        {

            // コマンドのインスタンスを作成

            ExecuteCommand = new RelayCommand(Execute, CanExecute);

        }


        private bool CanExecute(object parameter)

        {

            // ここでコマンドの実行可否を決定します

            return true;

        }


        private void Execute(object parameter)

        {

            // ここでコマンドの実行内容を記述します

            MessageBox.Show("Command executed!");

        }

    }


    public class RelayCommand : ICommand

    {

        private readonly Action<object> _execute;

        private readonly Func<object, bool> _canExecute;


        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)

        {

            _execute = execute ?? throw new ArgumentNullException(nameof(execute));

            _canExecute = canExecute;

        }


        public event EventHandler CanExecuteChanged

        {

            add { CommandManager.RequerySuggested += value; }

            remove { CommandManager.RequerySuggested -= value; }

        }


        public bool CanExecute(object parameter)

        {

            return _canExecute == null || _canExecute(parameter);

        }


        public void Execute(object parameter)

        {

            _execute(parameter);

        }

    }

}

```


このコードでは、CommandManager.RequerySuggested イベントに対して CanExecuteChanged イベントを追加および削除することで、コマンドの実行状態を再評価します。これにより、UI の状態が変更される度に CanExecute メソッドが呼び出され、コマンドの実行可否が動的に変更されます。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.18 08:11:12


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: