vendredi 18 août 2017

How Can I Check/UnCheck All Checkboxes in Listbox in C# WPF?

I have a listbox contains checkboxes in DataTemplate and I have two buttons "Select All" and "UnSelect All".I want to make that checkboxes to check all and uncheck all with clicking select and unselect buttons.How Can I do that?

Thanks for your answers in advance..

XAML CODE

  <StackPanel>
        <ListBox Name="lstUserDefination" 
 ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionMode="Multiple">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ListBoxItem>
                    <CheckBox Name="chkUser" Content="{Binding AuthorityName}"/>
                    </ListBoxItem>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>

C# CODE

   public partial class UserDefinationEdit : Window
{
    public ObservableCollection<Authority> authorityList { get; set; }

    public UserDefinationEdit()
    {
        InitializeComponent();
        CreateCheckBoxList();
        lstUserDefination.ItemsSource = authorityList;
    }


    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }

    public void CreateCheckBoxList()
    {
        authorityList = new ObservableCollection<Authority>();

        authorityList.Add(new Authority() {AuthorityValue = 0, AuthorityName = "0 - " });
        authorityList.Add(new Authority() { AuthorityValue = 1, AuthorityName = "1 - " });
        authorityList.Add(new Authority() { AuthorityValue = 2, AuthorityName = "2 - " });
        authorityList.Add(new Authority() { AuthorityValue = 3, AuthorityName = "3 - " });
        authorityList.Add(new Authority() { AuthorityValue = 4, AuthorityName = "4 - " });
        authorityList.Add(new Authority() { AuthorityValue = 5, AuthorityName = "5 - " });
        authorityList.Add(new Authority() { AuthorityValue = 6, AuthorityName = "6 - " });


        this.DataContext = this;
    }

    private void btnUnselectall_Click(object sender, RoutedEventArgs e)
    {
        lstUserDefination.UnselectAll();
    }

    private void btnSelectAll_Click(object sender, RoutedEventArgs e)
    {
        lstUserDefination.SelectAll();
    }

}
public class Authority
{
    public string AuthorityName { get; set; }
    public int AuthorityValue { get; set; }
    public bool IsChecked { get; set; }
}
}




Aucun commentaire:

Enregistrer un commentaire