回答編集履歴

1

見直しキャンペーン中

2023/07/25 16:01

投稿

TN8001
TN8001

スコア9337

test CHANGED
@@ -1,157 +1,79 @@
1
1
  解決されたようですが、閲覧者向けにタイトルを回収しておきます。
2
2
 
3
-
4
-
5
3
  本来`ListView`と`DataGrid`は役割が違います。
6
-
7
4
  表示するだけなら`ListView`でいいですし、項目の編集をするなら`DataGrid`です。
8
5
 
9
-
10
-
11
- ```xaml
6
+ ```xml
12
-
13
7
  <Window
14
-
15
8
  x:Class="Questions314032.MainWindow"
16
-
17
9
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
18
-
19
10
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
20
-
21
11
  Width="800"
22
-
23
12
  Height="450">
24
-
25
13
  <Grid>
26
-
27
14
  <ListView ItemsSource="{Binding People}">
28
-
29
15
  <ListView.View>
30
-
31
16
  <GridView>
32
-
33
17
  <GridViewColumn DisplayMemberBinding="{Binding Id}" Header="ID" />
34
-
35
18
  <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="名前" />
36
-
37
19
  <GridViewColumn Header="削除">
38
-
39
20
  <GridViewColumn.CellTemplate>
40
-
41
21
  <DataTemplate>
42
-
43
22
  <Button Content="削除" Click="Button_Click" />
44
-
45
23
  </DataTemplate>
46
-
47
24
  </GridViewColumn.CellTemplate>
48
-
49
25
  </GridViewColumn>
50
-
51
26
  </GridView>
52
-
53
27
  </ListView.View>
54
-
55
28
  </ListView>
56
-
57
29
  </Grid>
58
-
59
30
  </Window>
60
-
61
31
  ```
62
32
 
63
-
64
-
65
- ```C#
33
+ ```cs
66
-
67
34
  using System.Collections.ObjectModel;
68
-
69
35
  using System.Windows;
70
-
71
36
  using System.Windows.Controls;
72
37
 
73
-
74
-
75
38
  namespace Questions314032
76
-
77
39
  {
78
-
79
40
  public class Person
80
-
81
41
  {
82
-
83
42
  public int Id { get; }
84
-
85
43
  public string Name { get; }
86
-
87
44
  public Person(int id, string name) => (Id, Name) = (id, name);
88
-
89
45
  }
90
46
 
91
-
92
-
93
47
  public partial class MainWindow : Window
94
-
95
48
  {
96
-
97
49
  public ObservableCollection<Person> People { get; }
98
-
99
50
  public MainWindow()
100
-
101
51
  {
102
-
103
52
  InitializeComponent();
104
-
105
53
  DataContext = this;
106
54
 
107
-
108
-
109
55
  People = new()
110
-
111
56
  {
112
-
113
57
  new(1, "田中"),
114
-
115
58
  new(2, "佐々木"),
116
-
117
59
  };
118
-
119
60
  }
120
61
 
121
-
122
-
123
62
  private void Button_Click(object sender, RoutedEventArgs e)
124
-
125
63
  {
126
-
127
64
  if (sender is Button button)
128
-
129
65
  {
130
-
131
66
  People.Remove((Person)button.DataContext);
132
-
133
67
  }
134
-
135
68
  }
136
-
137
69
  }
138
-
139
70
  }
140
-
141
71
  ```
142
-
143
-
144
72
 
145
73
  ---
146
74
 
147
-
148
-
149
75
  特に指定がないので.NET 5.0で書きました^^
150
-
151
76
  .NET Framework 4.8等では、new()でエラーが出るので型を書いてください。
152
77
 
153
-
154
-
155
78
  [Target-typed new expressions - C# 9.0 specification proposals | Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new)
156
-
157
79
  [ターゲットからの new 型推論 | ++C++; // 未確認飛行 C](https://ufcpp.net/study/csharp/oo_construct.html#target-typed-new)