回答編集履歴

1

見直しキャンペーン中

2023/07/23 09:09

投稿

TN8001
TN8001

スコア9326

test CHANGED
@@ -1,67 +1,34 @@
1
1
  > DataContextへのViewModelの代入を削除したところ
2
-
3
2
  > e.ValueにViewDataのインスタンスが入っておりましたが、
4
3
 
5
-
6
-
7
4
  `DataContext`に`ViewModel`を、必ず入れなければならないと思い込んでいるんでしょうか?
8
-
9
5
  `ViewData`が入ってきているのですから、そのままバインドすればいいのですが。
10
-
11
6
  つまり`DependencyProperty`も不要です。
12
7
 
13
-
14
-
15
- ```xaml
8
+ ```xml
16
-
17
9
  <Button
18
-
19
10
  x:Class="Questions302443.TempButton"
20
-
21
11
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
22
-
23
12
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
24
-
25
13
  <Grid>
26
-
27
14
  <Grid.RowDefinitions>
28
-
29
15
  <RowDefinition Height="3*" />
30
-
31
16
  <RowDefinition />
32
-
33
17
  </Grid.RowDefinitions>
34
-
35
18
  <Image Source="{Binding Image}" />
36
-
37
19
  <Grid Grid.Row="1" Background="White">
38
-
39
20
  <TextBlock Text="{Binding Name}" TextAlignment="Center" />
40
-
41
21
  </Grid>
42
-
43
22
  </Grid>
44
-
45
23
  </Button>
46
-
47
24
  ```
48
-
49
-
50
25
 
51
26
  > DataContextにViewModelを代入してる場合なぜe.ValueはNullになってしまうのでしょうか?
52
27
 
53
-
54
-
55
28
  いいえ`TempButtonViewModel`が入っています。
56
-
57
29
  `as ViewData`としたため、`null`になりました。
58
30
 
59
-
60
-
61
31
  `ListView`等のコレクションを扱うコントロールは、個々のアイテムに`DataContext`経由でデータを渡します。
62
-
63
32
  しかし`TempButton`内で`DataContext`を設定した場合は、そちらが優先されてしまいます。
64
33
 
65
-
66
-
67
34
  そもそもユーザーコントロールやテンプレートコントロール内で、自身の`DataContext`を設定すること自体がイレギュラーだと思います(全くないとまでは言えませんが)