2017-07-18 232 views
0

我想通過選擇帶有「以上所有」的複選框名稱來選中所有複選框。 複選框是在列表框中選擇所有複選框WPF

<ListBox SelectionMode="Multiple" 
     BorderThickness="0" 
     ItemsSource="{Binding QuestionThreeSelection}" 
     SelectedItem="{Binding QuestionThreeSelection}" 
     Name="listBoxList" 
     SelectionChanged="listBoxList_SelectionChanged"> 
    <ListBox.InputBindings> 
     <KeyBinding Command="ApplicationCommands.SelectAll" 
        Modifiers="Ctrl" 
        Key="A" /> 
    </ListBox.InputBindings> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <CheckBox Checked="CheckBox_Checked_1" 
         Content="{Binding SourceName}" 
         IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

回守則

private void CheckBox_Checked_1(object sender, RoutedEventArgs e) 
{   
    var oo = listBoxList; 
    CheckBox cb = (CheckBox)sender; 
    //var w=e; 

    IEnumerable<AddSource> listallityem = ((IEnumerable<AddSource>)listBoxList.Items.SourceCollection).Where(r => r.IsSelected == false); 
    //IEnumerable<AddSource> listallityem1 = ((IEnumerable<AddSource>)listBoxList.Items.SourceCollection); 

    AddSource vv = cb.DataContext as AddSource; 
    if ((bool) cb.IsChecked) 
    { 

    } 

    if (vv.SourceName== "All of the above") 
    { 
     r = listBoxList.ItemsSource; 

     foreach (AddSource item in wer) 
     { 
      item.IsSelected = true; // false in case of unselect 
     } 
    } 
} 

有人能提出一個方法?

+0

你可以在ViewModel中處理所有的,因爲你有綁定。 – Rekshino

回答

1

您可以處理CheckedUnchecked事件爲貴「的所有上述」 CheckBox是這樣的:

private void CheckBox_Checked(object sender, RoutedEventArgs e) 
{ 
    SelectAll(true); 
} 

private void CheckBox_Unchecked(object sender, RoutedEventArgs e) 
{ 
    SelectAll(false); 
} 

private void SelectAll(bool select) 
{ 
    var all = listBoxList.ItemsSource as IEnumerable<AddSource>; 
    if (all != null) 
    { 
     foreach (var source in all) 
      source.IsSelected = select; 
    } 
} 

確保您AddSource類實現INotifyPropertyChanged和的二傳手提高PropertyChanged事件財產。

+0

是的確切原因是我沒有實現INotifyPropertyChanged.now它的工作原理..謝謝 – MSKP