清除CheckBoxList的值

本文关键字:的值 CheckBoxList 清除 | 更新日期: 2023-09-27 18:05:10

我有一个带有复选框的listBox,当事件结束时,我需要取消每个复选框。

这是我的xaml,但在代码中我如何清除这些值?由于

<ListBox Name="_employeeListBox" ItemsSource="{Binding employeeList}" Margin="409,27,41,301">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <CheckBox Grid.Column="0" Name="CheckBoxZone" Content="{Binding OperatorNum}" Tag="{Binding TheValue}" Checked="CheckBoxZone_Checked"/>
                <TextBlock Grid.Column="1"></TextBlock>
                <TextBlock Grid.Column="2" Text="{Binding Name}"></TextBlock>
                <TextBlock Grid.Column="3"></TextBlock>
                <TextBlock Grid.Column="4" Text="{Binding LastName}"></TextBlock>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
  private void _searchProjectsbyEmployeebutton_Click_1(object sender, RoutedEventArgs e)
    {
        List<EmployeebyProject> employeebyProjectList = new List<EmployeebyProject>();
        if (EmployeeCollectionToInsert.Count != 0)
        {
            foreach (var employee in EmployeeCollectionToInsert)
            {
                foreach(var employeebyProject in employee.EmployeebyProject)
                {
                    employeebyProjectList.Add(employeebyProject);
                }
            }
            LoadEmployeebyProject(employeebyProjectList);  
            //HERE I NEED UNCHECKED the ListBoxChecked.             
        }
        else { MessageBox.Show("Please select an employee to search his project."); }
    }

清除CheckBoxList的值

您将ItemsSource绑定到ListBox中,ListBox使用VirtualizingStackPanel作为其ItemsPanel,因此所有ListBoxItem容器可能会或可能不会在任何给定时间生成。
因此,即使你搜索可视化树等来取消选中所有的复选框,你也不能确定你已经选中了它们。

我建议您将IsChecked绑定到与您定义的OperatorNum相同的类中的新属性(从您的问题的外观来看,可能是Employee或类似)。这样,要取消复选框,您所需要做的就是在源类中将IsChecked设置为False
还要确保你实现了INotifyPropertyChanged

例子Xaml

<CheckBox Grid.Column="0"
          Name="CheckBoxZone"
          Content="{Binding OperatorNum}"
          Tag="{Binding TheValue}"
          IsChecked="{Binding IsChecked}"/>
员工

public class Employee : INotifyPropertyChanged
{
    private bool m_isChecked;
    public bool IsChecked
    {
        get { return m_isChecked; }
        set
        {
            m_isChecked = value;
            OnPropertyChanged("IsChecked");
        }
    }
    // Etc..
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

这篇文章解释了如何获得基于ListBoxTemplate的项目。你可以用类似的方法找到CheckBox一旦你找到了CheckBox,勾选或取消勾选是很简单的