2013-07-12 112 views
1

我有一個名爲People的類,它具有STRING nameSTRING ImgPath。我做了一個LISTlistOfPeople這是icCheckBox的來源。如何獲取數據模板中複選框的isChecked屬性的值

<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。我怎麼能這樣做?

回答

1

這不是一種方法。使用MouseUp是針對MVVM的。

您應該綁定到列表中每個元素的PropertyChanged事件。當propertyName被選中時,您的監聽虛擬機會爲您重新創建已選中的人員列表。

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 
    } 
} 
+0

你能不能解釋一下?這個名字永遠不會改變,只是它是被檢查還是不被檢查。我是否必須創建自己的isChecked屬性,而不是在複選框中創建一個? – meisenman

+0

這裏你是:) – dzendras

+0

人是一個模型。你用ViewModel東西(INPC)包裝它。在VM中有一個地方可以添加額外的屬性(如IsChecked)。最後,你有「主」視圖模型,其中聚合所有項目是列表。它綁定到他們的事件,以便了解用戶切換複選框。 – dzendras

0
  1. 您仍然可以通過投發件人複選框得到複選框IsChecked財產。
  2. 但是,您不應該在代碼後面添加事件處理函數DataTemplate
  3. 建議的方法是使用DataBinding。爲Person類創建一個bool屬性,並在DataTemplate中將IsChecked綁定到它。在你的布爾屬性的setter中,做填充工作。
+0

假設Person類是一個模型,你的第三條建議是錯誤的。你應該永遠不要修改模型來適應ViewModel。 – dzendras

+1

這意味着你的假設是錯誤的。我假設人是ViewModel。 –

+0

非常好然後:) – dzendras

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 reference

相關問題