1

I have a class called People which has STRING name and STRING ImgPath. I make a LIST listOfPeople which is the source of 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>

I would like to go through each time a checkbox is changed and populate a new list of the people that are checked.

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
    }

I cannot get the isChecked Property of the checkbox because it is a datatemplate. How could I do this?

4

3 回答 3

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
    }
}
于 2013-07-12T18:45:28.023 回答
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>

EventToCommand 参考

于 2013-07-12T20:10:36.230 回答
0
  1. 您仍然可以IsChecked通过将发件人转换为 Checkbox 从 Checkbox 获取属性。
  2. 但是,您不应在DataTemplate.
  3. 建议的方法是使用 DataBinding。为 Person 类创建一个 bool 属性并IsCheckedDataTemplate. 在您的 bool 属性的设置器中,执行填充工作。
于 2013-07-12T18:50:24.633 回答