프로그래밍/WPF

[WPF] DataGrid 행 더블 클릭 시 Command 실행하기

흔한티벳여우 2023. 11. 3. 08:47
반응형

WPF에서 MVVM 패턴을 사용하는 경우, DataGrid의 행을 더블 클릭할 때 특정 Command를 실행하고자 할 수 있습니다. 이 작업을 수행하기 위해서는 Interaction.Behaviors를 활용하는 것이 일반적입니다. 오늘은 DataGrid 행 더블 클릭에 Command를 연결하고 CommandParameter로 선택된 행의 아이템을 전달하는 방법을 살펴보겠습니다.

 

1단계: Behavior 클래스 생성

먼저, 행 더블 클릭 시 실행할 Behavior 클래스를 생성해야 합니다. 이 클래스는 System.Windows.Interactivity.Behavior를 상속받아야 합니다. 그리고 Command와 CommandParameter를 DependencyProperty로 선언하여, XAML에서 Binding이 가능하게 만들어야 합니다.

using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Controls;

public class DataGridDoubleClickBehavior : Behavior<DataGrid>
{
    // Command DependencyProperty
    public static readonly DependencyProperty CommandProperty = 
        DependencyProperty.Register(
            "Command", 
            typeof(ICommand), 
            typeof(DataGridDoubleClickBehavior), 
            new PropertyMetadata(null));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    // CommandParameter DependencyProperty
    public static readonly DependencyProperty CommandParameterProperty = 
        DependencyProperty.Register(
            "CommandParameter", 
            typeof(object), 
            typeof(DataGridDoubleClickBehavior), 
            new PropertyMetadata(null));

    public object CommandParameter
    {
        get { return GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.MouseDoubleClick += AssociatedObject_MouseDoubleClick;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        this.AssociatedObject.MouseDoubleClick -= AssociatedObject_MouseDoubleClick;
    }

    private void AssociatedObject_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        // Hit test를 사용하여 클릭된 요소가 데이터 행인지 확인
        var hit = e.OriginalSource as DependencyObject;
        while (hit != null && !(hit is DataGridRow))
        {
            hit = VisualTreeHelper.GetParent(hit);
        }

        // 클릭된 요소가 데이터 행일 경우에만 Command 실행
        if (hit is DataGridRow)
        {
            if (Command != null && Command.CanExecute(CommandParameter))
            {
                Command.Execute(CommandParameter);
            }
        }
    }
}

 

2단계: XAML에서 Behavior 적용

DataGridDoubleClickBehavior 클래스가 준비되었다면, 이제 XAML에서 해당 Behavior를 DataGrid에 적용할 수 있습니다.

<DataGrid ItemsSource="{Binding YourItemsCollection}">
    <Interactivity:Interaction.Behaviors>
        <local:DataGridDoubleClickBehavior Command="{Binding RowDoubleClickCommand}"
                                           CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
    </Interactivity:Interaction.Behaviors>
    <!-- 나머지 DataGrid 정의 -->
</DataGrid>

 

3단계: ViewModel에서 Command 구현

마지막으로, ViewModel 내에서 RowDoubleClickCommand를 구현합니다. RelayCommand 또는 이와 유사한 ICommand 구현을 사용하여 Command를 정의할 수 있습니다.

public class YourViewModel
{
    public ICommand RowDoubleClickCommand { get; }

    public YourViewModel()
    {
        RowDoubleClickCommand = new RelayCommand(ExecuteRowDoubleClick);
    }

    private void ExecuteRowDoubleClick(object parameter)
    {
        // parameter에는 선택된 DataGrid 행의 아이템이 전달됩니다.
        // 여기서 필요한 작업을 수행합니다.
    }
}

 

이러한 방법을 통해 DataGrid의 행을 더블 클릭할 때 원하는 Command를 실행하고, 해당 행의 데이터를 CommandParameter로 전달할 수 있습니다. 이 방식은 MVVM 패턴의 지침을 따르며, 코드의 가독성과 유지보수성을 높입니다.

 

반응형