我有一个名为People的课程,其中包含STRING name
和STRING ImgPath
。我制作LIST
listOfPeople
,这是icCheckBox
。
<DataTemplate x:Key="cBoxTemp">
<StackPanel Orientation="Horizontal" Width="Auto" Height="Auto">
<CheckBox Content="{Binding name}" MouseUp="CheckBox_MouseUp"/>
</StackPanel>
</DataTemplate>
XAML
<ItemsControl Name="icCheckBox" Grid.Column="0" ItemTemplate="{StaticResource cBoxTemp}" Height="Auto" Width="Auto">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
我希望每次更改复选框时都会检查并填写一个新的已检查人员列表。
private void CheckBox_MouseUp(object sender, MouseButtonEventArgs e)
{
// listOfSelectedPeople = new List<Person>();
// For Each (Person e in listOfPeople)
// if(cur.isChecked == true)
// ListofSelectedPeople.add(current);
// ... Once I have this List populated my program will run
}
我无法获取复选框的isChecked
属性,因为它是datatemplate
。我怎么能这样做?
答案 0 :(得分:1)
这不是一种方法。使用MouseUp是针对MVVM的。
您应该绑定到列表中每个元素的PropertyChanged事件。当propertyName为Checked时,您的侦听VM将为您重新创建已检查人员列表。
class Person //Model
{
public string Name {get;set;}
public string ImgPath {get;set;}
}
class PersonViewModel : INotifyPropertyChanged
{
readonly Person _person;
public string Name {get {return _person.Name;}}
public string ImgPath {get {return _person.ImgPath; }}
public bool IsChecked {get;set;} //implement INPC here
public PersonViewModel(Person person)
{
_person = person;
}
}
class ParentViewModel
{
IList<PersonViewModel> _people;
public ParentViewModel(IList<PersonViewModel> people)
{
_people = people;
foreach (var person in people)
{
person.PropertyChanged += PropertyChanged;
}
}
void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//Recreate checked people list
}
}
答案 1 :(得分:0)
IsChecked
属性。DataTemplate
。IsChecked
中将DataTemplate
绑定到它。在您的bool属性的setter中,进行填充工作。答案 2 :(得分:0)
我建议你使用EventToCommand并将Checked事件绑定到视图模型中的命令,并在命令参数中发送当前的People对象。
<CheckBox...>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<cmd:EventToCommand Command="{Binding PopulateCommad}"
CommandParameter="{Binding }"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>