ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [WPF] Datagrid 내에서 항목 삭제하기
    C# 2024. 5. 28. 11:55

    DataGrid 내에 삭제 버튼을 포함하고, 각 행의 항목을 삭제하는 기능을 구현하려면, DataGrid의 각 행에 버튼을 추가하여 해당 버튼을 클릭했을 때 해당 행을 삭제하는 방법을 사용합니다. 이를 위해 DataGridTemplateColumn을 사용하여 각 행에 삭제 버튼을 추가하고, 버튼 클릭 이벤트를 ViewModel의 Command로 바인딩합니다.

    1. DataGrid에 삭제 버튼 추가

    먼저 DataGrid의 각 행에 삭제 버튼을 추가하고, 버튼 클릭 이벤트를 Command로 바인딩하는 XAML을 작성합니다.

    View (XAML)

    <Window x:Class="YourNamespace.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
            xmlns:local="clr-namespace:YourNamespace"
            Title="MainWindow" Height="350" Width="525">
        <Window.DataContext>
            <local:MainViewModel />
        </Window.DataContext>
        <Grid>
            <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                    <DataGridCheckBoxColumn Header="IsChecked" Binding="{Binding IsChecked}" />
                    <DataGridTemplateColumn Header="Actions">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Delete" Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding}" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>

    2. ViewModel 구현

    ViewModel에서 아이템 목록과 삭제 커맨드를 정의하고, 삭제 로직을 구현합니다.

    ViewModel (C#)

    using System.Collections.ObjectModel;
    using Systehttp://m.Windows.Input;

    public class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<ItemViewModel> Items { get; }

        public ICommand DeleteCommand { get; }

        public MainViewModel()
        {
            Items = new ObservableCollection<ItemViewModel>
            {
                new ItemViewModel { Name = "Item1", IsChecked = false },
                new ItemViewModel { Name = "Item2", IsChecked = true },
                // Add more items as needed
            };

            DeleteCommand = new RelayCommand<ItemViewModel>(OnDelete);
        }

        private void OnDelete(ItemViewModel item)
        {
            if (item != null)
            {
                Items.Remove(item);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class ItemViewModel : INotifyPropertyChanged
    {
        private bool _isChecked;
        public string Name { get; set; }

        public bool IsChecked
        {
            get => _isChecked;
            set
            {
                if (_isChecked != value)
                {
                    _isChecked = value;
                    OnPropertyChanged(nameof(IsChecked));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    RelayCommand 구현

    RelayCommand는 다음과 같이 구현할 수 있습니다.

    public class RelayCommand<T> : ICommand
    {
        private readonly Action<T> _execute;
        private readonly Predicate<T> _canExecute;

        public RelayCommand(Action<T> execute) : this(execute, null) { }

        public RelayCommand(Action<T> execute, Predicate<T> canExecute)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

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

    설명

    1. XAML 설정: DataGrid의 각 행에 Delete 버튼을 추가합니다. 이 버튼은 DeleteCommand에 바인딩되며, CommandParameter로 해당 행의 ItemViewModel을 전달합니다.
    2. ViewModel 설정: DeleteCommand는 선택된 행의 ItemViewModel을 받아 Items 컬렉션에서 해당 항목을 제거합니다.

    이렇게 설정하면 DataGrid 내의 특정 셀을 선택하여 해당 행을 삭제하는 기능을 MVVM 패턴으로 구현할 수 있습니다. DataGrid의 각 행에 포함된 삭제 버튼을 통해 행을 삭제할 수 있으며, 이 모든 동작은 ViewModel에서 처리됩니다.

    'C#' 카테고리의 다른 글

    문자열 예제  (0) 2021.10.02
    Stream 에서 한줄씩 읽기  (0) 2021.10.02
    Save file. SaveFileDialog  (0) 2021.10.02
    파일 선택. File picker  (0) 2021.10.02
    파일 읽기, StreamReader  (0) 2021.10.02
Designed by Tistory.