回答編集履歴

1

add code

2017/03/13 11:29

投稿

Tak1wa
Tak1wa

スコア4791

test CHANGED
@@ -3,3 +3,101 @@
3
3
 
4
4
 
5
5
  単一選択モードであれば、ListBox.SelectedItemにViewModelのプロパティをバインドさせて、ViewModel側へ選択インスタンスを通知する方法もあります。
6
+
7
+
8
+
9
+ ```XML
10
+
11
+ <ListBox Name="listbox" Grid.Column="0"
12
+
13
+ ItemsSource="{Binding People}"
14
+
15
+ SelectedItem="{Binding SelectedPerson}">
16
+
17
+ <ListBox.ItemTemplate>
18
+
19
+ <HierarchicalDataTemplate>
20
+
21
+ <TextBlock Text="{Binding Name}" />
22
+
23
+ </HierarchicalDataTemplate>
24
+
25
+ </ListBox.ItemTemplate>
26
+
27
+ </ListBox>
28
+
29
+ ```
30
+
31
+
32
+
33
+ ```C#
34
+
35
+ public class MainWindowViewModel : INotifyPropertyChanged
36
+
37
+ {
38
+
39
+ public ObservableCollection<Person> People { get; set; }
40
+
41
+ = new ObservableCollection<Person>();
42
+
43
+
44
+
45
+ private Person _SelectedPerson = null;
46
+
47
+ public Person SelectedPerson
48
+
49
+ {
50
+
51
+ get { return _SelectedPerson; }
52
+
53
+ set
54
+
55
+ {
56
+
57
+ _SelectedPerson = value;
58
+
59
+ OnPropertyChanged();
60
+
61
+ }
62
+
63
+ }
64
+
65
+
66
+
67
+ public MainWindowViewModel()
68
+
69
+ {
70
+
71
+ People.Add(new Person { Name = "Human01" });
72
+
73
+ People.Add(new Person { Name = "Human02" });
74
+
75
+ People.Add(new Person { Name = "Human03" });
76
+
77
+ People.Add(new Person { Name = "Human04" });
78
+
79
+ People.Add(new Person { Name = "Human05" });
80
+
81
+ }
82
+
83
+
84
+
85
+ public event PropertyChangedEventHandler PropertyChanged;
86
+
87
+
88
+
89
+ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
90
+
91
+ {
92
+
93
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
94
+
95
+ }
96
+
97
+ }
98
+
99
+ ```
100
+
101
+
102
+
103
+ ※DelegateCommandは今回の問題には不要なので割愛しました。