C#

[C#]Command Binding 예시

수학소년 2024. 2. 27. 00:15

WPF Application, 8.0 LTS로 Application을 만들고

Button만들고

 

1. MainWindow.xaml

<Window x:Class="WpfApp10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp10"
        xmlns:viewModel="clr-namespace:WpfApp10.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <viewModel:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Button Content="Button" HorizontalAlignment="Center" Height="113" Margin="0,104,0,0" VerticalAlignment="Top" Width="210"
                Command="{Binding ButtonCommand}"
        />
    </Grid>
</Window>

namespace가 WpfApp10.ViewModels이고

MainViewModel이라는 class에

ButtonCommand라는 Property를 만들어야 함

 

2. Common/RelayCommand.cs

using System.Windows.Input;

namespace WpfApp10.Common
{
    class RelayCommand : ICommand
    {
        private readonly Action<object> _executeAction;
        public RelayCommand(Action<object> executeAction)
        {
            _executeAction = executeAction;
        }
        public bool CanExecute(object? parameter) => true;
        public void Execute(object? parameter) => _executeAction(parameter);

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

RelayCommand라는 ICommand의 구현체는 좀 유명한가봄?

여러 예제에서 같은 class명으로 자주 등장함

공통코드인듯한데, 프로젝트 스타일에 맞게 자유롭게 변형하여 쓰는듯함

 

3. ViewModels/MainViewModel.cs

using System.Windows;
using WpfApp10.Common;

namespace WpfApp10.ViewModels
{
    class MainViewModel
    {
        public RelayCommand ButtonCommand { get; set; }

        public MainViewModel()
        {
            this.ButtonCommand = new RelayCommand(CallCommand);
        }

        private void CallCommand(object param)
        {
            MessageBox.Show("dddddd");
        }
    }
}

CallCommand에 parameter가 필요없어서 CallCommand() 로 만들었더니 컴파일 오류가 뜸

Action<object>는 parameter를 반드시 보내줘야 하나봄