回答編集履歴

1

見直しキャンペーン中

2023/07/27 14:48

投稿

TN8001
TN8001

スコア9326

test CHANGED
@@ -1,133 +1,66 @@
1
1
  `MainWrapPanel`の子だけを検知できればいいのなら、`WrapPanel`を継承し`OnVisualChildrenChanged`をオーバーライドすればいいでしょう(試したことのリンク記事はそういう意味です)
2
2
 
3
-
4
-
5
3
  ですがやりたいことって恐らくそういう意味じゃないんですよね?
6
-
7
4
  どこに置いたボタン(等)でもイベントを拾いたいって意味ですよね。
8
5
 
9
-
10
-
11
6
  WPFはルーティングイベントという大変便利な仕組みがあります。
12
-
13
7
  `MainWindow`で一括して`Button.Click`を拾うことができます。
14
-
15
-
16
-
17
8
  [ルーティング イベントの概要 - WPF .NET Framework | Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/desktop/wpf/advanced/routed-events-overview)
18
-
19
-
20
9
 
21
10
  イベントによっては(例えば`Button.MouseDown`)処理済みになって来ないので、トンネルイベント(`Previewなんちゃら`)を使用してください。
22
11
 
23
-
24
-
25
- ```xaml
12
+ ```xml
26
-
27
13
  <Window
28
-
29
14
  x:Class="Questions342011.MainWindow"
30
-
31
15
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
32
-
33
16
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
34
-
35
17
  Width="800"
36
-
37
18
  Height="450"
38
-
39
19
  Button.Click="Window_Button_Click">
40
-
41
20
  <WrapPanel Name="MainWrapPanel">
42
-
43
21
  <Button
44
-
45
22
  Width="75"
46
-
47
23
  Margin="10"
48
-
49
24
  Click="AddButton_Click"
50
-
51
25
  Content="Add" />
52
-
53
26
  </WrapPanel>
54
-
55
27
  </Window>
56
-
57
28
  ```
58
29
 
59
-
60
-
61
- ```C#
30
+ ```cs
62
-
63
31
  using System.Diagnostics;
64
-
65
32
  using System.Windows;
66
-
67
33
  using System.Windows.Controls;
68
34
 
69
-
70
-
71
35
  namespace Questions342011
72
-
73
36
  {
74
-
75
37
  public partial class MainWindow : Window
76
-
77
38
  {
78
-
79
39
  public MainWindow() => InitializeComponent();
80
40
 
81
-
82
-
83
41
  private int count;
84
-
85
42
  private void AddButton_Click(object sender, RoutedEventArgs e)
86
-
87
43
  {
88
-
89
44
  var button = new Button()
90
-
91
45
  {
92
-
93
46
  Content = $"Button{++count}",
94
-
95
47
  Width = 75,
96
-
97
48
  Margin = new Thickness(10),
98
-
99
49
  };
100
-
101
50
  button.Click += Button_Click;
102
-
103
51
  MainWrapPanel.Children.Add(button);
104
-
105
52
  }
106
53
 
107
-
108
-
109
54
  private void Button_Click(object sender, RoutedEventArgs e)
110
-
111
55
  {
112
-
113
56
  Debug.WriteLine($"Button_Click: {(e.Source as Button).Content}");
114
-
115
57
  //e.Handled = true; // 処理済みにすると↓に来なくなるので注意
116
-
117
58
  }
118
59
 
119
-
120
-
121
60
  private void Window_Button_Click(object sender, RoutedEventArgs e)
122
-
123
61
  {
124
-
125
62
  Debug.WriteLine($"Window_Button_Click: {(e.Source as Button).Content}");
126
-
127
63
  }
128
-
129
64
  }
130
-
131
65
  }
132
-
133
66
  ```