簡體   English   中英

如何獲取數據模板中Checkbox的isChecked屬性的值

[英]How to get the value of isChecked property of a Checkbox in a data template

我有一個名為People的類,它具有STRING nameSTRING 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
    }
}
  1. 您仍然可以通過將發件人發送給Checkbox,從Checkbox獲取IsChecked屬性。
  2. 但是,您不應在代碼后面為DataTemplate添加事件處理程序。
  3. 建議的方法是使用DataBinding。 為Person類創建一個bool屬性,並將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>

EventToCommand參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM