4

I have a list of strings and I want to convert it to checkboxes control in scrollviewer control. How can I do this? Any ideas? The list consists of courses and I want to make it as checkboxes so student can choose some of them.

Langdon
  • 27
  • 1
  • 6
kartal
  • 17,436
  • 34
  • 100
  • 145

3 Answers3

2

XAML Part :

   <ScrollViewer>
        <ListBox ItemsSource="{Binding .}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Path=.}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </ScrollViewer>

Code-behind part :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new string[] {"course1", "course2"};
    }
}
Stecya
  • 22,896
  • 10
  • 72
  • 102
0

Would a listbox control with Checkbox as its items work for you?

This is part of a WPF Xaml code that I wrote for a checkbox list:

        <ListBox Name="CheckBoxDataListBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Width="Auto" Height="20" Margin="0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Grid Grid.Column="0">
                            <CheckBox HorizontalAlignment="Center" Padding="0" DataContext="{Binding}" VerticalAlignment="Center" IsChecked="{Binding IsSelected}"></CheckBox>
                        </Grid>
                        <Label Name="SelectLabel" Grid.Column="1"  Padding="0" DataContext="{Binding}" Content="{Binding Value}"></Label>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
Viv
  • 2,515
  • 2
  • 22
  • 26
  • when I add items in it it just add labels not checkbox can you text it again or discuss how it work ? – kartal Mar 29 '11 at 17:58
  • Did you make sure you got the grid columns correct? the Label may have been placed over the checkbox control? Make sure their is enough column width. Comment out the label and see if the checkbox is displayed. – Viv Mar 29 '11 at 18:22
  • I copied the code from my project where the text needs to be displayed on the other side of the checkbox. I couldn't do it with the checkbox available (or couldn't find out how). – Viv Mar 29 '11 at 18:26
  • @Vivek - in that case you just need to set `FlowDirection="RightToLeft"` – Stecya Mar 29 '11 at 18:38
0

You need to bind the collection of strings as the ItemsSource of a ListBox and set ListBox.ItemTemplate to a DataTemplate that includes a checkbox.

For example, see WPF ListBoxItem selection problem.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806