[英]How to get the value of isChecked property of a Checkbox in a data template
我有一個名為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
。 我該怎么辦?
那不是走的路。 使用MouseUp針對MVVM。
您應該綁定到列表中每個元素的PropertyChanged事件。 當propertyName被選中時,您的偵聽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
}
}
IsChecked
屬性。 DataTemplate
添加事件處理程序。 IsChecked
綁定到DataTemplate
。 在布爾屬性的設置器中,進行填充工作。 我建議您使用EventToCommand並將Checked事件綁定到視圖模型中的命令,並在command參數中發送當前的People對象。
<CheckBox...>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<cmd:EventToCommand Command="{Binding PopulateCommad}"
CommandParameter="{Binding }"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.