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

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

2024.06.08
XML
カテゴリ: WPFC#.NET


C# WPFで`DataGrid`に新しい行を追加する方法はいくつかありますが、最も簡単な方法の一つは、`ObservableCollection`を使用してデータソースを管理し、新しい項目をコレクションに追加することです。これにより、`DataGrid`が自動的に更新され、新しい行が表示されます。


以下に、ボタンをクリックして新しい行を追加する具体的な例を示します。


### 1. モデルクラスの作成


まず、データを表すモデルクラスを定義します。


```csharp

public class Person

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

}

```


### 2. ViewModelクラスの作成


次に、`ObservableCollection`を使用してデータを管理する`ViewModel`クラスを作成します。


```csharp

using System.Collections.ObjectModel;

using System.ComponentModel;

using System.Windows.Input;


namespace WpfApp

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private ObservableCollection<Person> _people;


        public ObservableCollection<Person> People

        {

            get => _people;

            set

            {

                _people = value;

                OnPropertyChanged(nameof(People));

            }

        }


        public ICommand AddPersonCommand { get; }


        public MainViewModel()

        {

            People = new ObservableCollection<Person>

            {

                new Person { FirstName = "John", LastName = "Doe", Age = 30 },

                new Person { FirstName = "Jane", LastName = "Smith", Age = 25 },

                new Person { FirstName = "Sam", LastName = "Johnson", Age = 40 }

            };


            AddPersonCommand = new RelayCommand(AddPerson);

        }


        private void AddPerson()

        {

            People.Add(new Person { FirstName = "New", LastName = "Person", Age = 20 });

        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected void OnPropertyChanged(string propertyName)

        {

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        }

    }


    public class RelayCommand : ICommand

    {

        private readonly Action _execute;

        private readonly Func<bool> _canExecute;


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

        {

            _execute = execute;

            _canExecute = canExecute;

        }


        public bool CanExecute(object parameter) => _canExecute == null || _canExecute();


        public void Execute(object parameter) => _execute();


        public event EventHandler CanExecuteChanged

        {

            add => CommandManager.RequerySuggested += value;

            remove => CommandManager.RequerySuggested -= value;

        }

    }

}

```


### 3. Viewの作成(XAML)


最後に、`DataGrid`と新しい行を追加するためのボタンを含むビューを作成します。


```xml

<Window x:Class="WpfApp.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"

        mc:Ignorable="d"

        xmlns:local="clr-namespace:WpfApp"

        Title="MainWindow" Height="350" Width="525">

    <Window.DataContext>

        <local:MainViewModel />

    </Window.DataContext>

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto" />

            <RowDefinition Height="*" />

        </Grid.RowDefinitions>


        <Button Content="Add Person" Command="{Binding AddPersonCommand}" Margin="10" />


        <DataGrid Grid.Row="1" ItemsSource="{Binding People}" AutoGenerateColumns="True" 

                  CanUserAddRows="False" CanUserDeleteRows="True" Margin="10"/>

    </Grid>

</Window>

```


### 完成したコード


以下に、すべてのファイルを統合したプロジェクト構造を示します。


#### MainWindow.xaml


```xml

<Window x:Class="WpfApp.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"

        mc:Ignorable="d"

        xmlns:local="clr-namespace:WpfApp"

        Title="MainWindow" Height="350" Width="525">

    <Window.DataContext>

        <local:MainViewModel />

    </Window.DataContext>

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto" />

            <RowDefinition Height="*" />

        </Grid.RowDefinitions>


        <Button Content="Add Person" Command="{Binding AddPersonCommand}" Margin="10" />


        <DataGrid Grid.Row="1" ItemsSource="{Binding People}" AutoGenerateColumns="True" 

                  CanUserAddRows="False" CanUserDeleteRows="True" Margin="10"/>

    </Grid>

</Window>

```


#### MainWindow.xaml.cs


```csharp

using System.Windows;


namespace WpfApp

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

    }

}

```


#### MainViewModel.cs


```csharp

using System.Collections.ObjectModel;

using System.ComponentModel;

using System.Windows.Input;


namespace WpfApp

{

    public class MainViewModel : INotifyPropertyChanged

    {

        private ObservableCollection<Person> _people;


        public ObservableCollection<Person> People

        {

            get => _people;

            set

            {

                _people = value;

                OnPropertyChanged(nameof(People));

            }

        }


        public ICommand AddPersonCommand { get; }


        public MainViewModel()

        {

            People = new ObservableCollection<Person>

            {

                new Person { FirstName = "John", LastName = "Doe", Age = 30 },

                new Person { FirstName = "Jane", LastName = "Smith", Age = 25 },

                new Person { FirstName = "Sam", LastName = "Johnson", Age = 40 }

            };


            AddPersonCommand = new RelayCommand(AddPerson);

        }


        private void AddPerson()

        {

            People.Add(new Person { FirstName = "New", LastName = "Person", Age = 20 });

        }


        public event PropertyChangedEventHandler PropertyChanged;


        protected void OnPropertyChanged(string propertyName)

        {

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        }

    }


    public class RelayCommand : ICommand

    {

        private readonly Action _execute;

        private readonly Func<bool> _canExecute;


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

        {

            _execute = execute;

            _canExecute = canExecute;

        }


        public bool CanExecute(object parameter) => _canExecute == null || _canExecute();


        public void Execute(object parameter) => _execute();


        public event EventHandler CanExecuteChanged

        {

            add => CommandManager.RequerySuggested += value;

            remove => CommandManager.RequerySuggested -= value;

        }

    }

}

```


#### Person.cs


```csharp

namespace WpfApp

{

    public class Person

    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

    }

}

```


この例では、`AddPersonCommand`を`RelayCommand`クラスを使用して実装し、ボタンをクリックすると`AddPerson`メソッドが呼び出され、新しい`Person`オブジェクトが`People`コレクションに追加されます。`DataGrid`は`ObservableCollection`にバインドされているため、新しい行が自動的に表示されます。






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

Last updated  2024.06.08 22:10:43


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

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