Filling a StackPanel with a checkbox from a database

I am new to WPF. I have a page that displays data from an SQL database using L2S. L2Sreturns DataTablethat contains all the available options for selection for a specific area. Every row returned from the database should be checkbox, and I want to put these checkboxes in stackpanel.

Am I considering data binding to stackpanel? This is wrong ... I assumed that I needed to go through DataTableand create checkbox elements for each line, and then add them at run time to stackpanel. It's right? Returns part of DataTablemy problem?

I see that it stackpanelhas a property DataContext, but I cannot just establish that it would not know that each element a checkbox, right?

+3
source share
2 answers

You probably need an ItemsControl element. This allows you to represent a number of elements using the specified DataTemplate. You can do this in the ItemsControl line:

   <ItemsControl ItemsSource="{Binding MyCollectionOfItems}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding NameOfTheCheckedPropertyOnEachItem}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>  

or explicitly reference the data template from the resource ... something more similar:

    <!-- In some parent resource section -->
    <DataTemplate x:Key="MyDataTemplateName">
        <CheckBox IsChecked="{Binding NameOfTheCheckedPropertyOnEachItem}"/>
    </DataTemplate>

    <!-- ... -->

    <ItemsControl ItemsSource="{Binding MyCollectionOfItems}" ItemTemplate="{StaticResource MyDataTemplateName}">
    </ItemsControl>

Or you can define a DataTemplate that defines the look of your related class. (Note that if your Linq-to-SQL is projected into an anonymous type, this is not an option). Sort of:

        <!-- In some parent resource section -->
        <DataTemplate DataType="{x:Type MyBoundClass}">
            <CheckBox IsChecked="{Binding NameOfTheCheckedPropertyOnEachItem}"/>
        </DataTemplate>

    <!-- ... -->

    <ItemsControl ItemsSource="{Binding MyCollectionOfItems}">
    </ItemsControl>

WPF DataTemplate, DataType . , , .

DataContext Stackpanel, . {Binding ...}. , , ItemsControl ItemsSource.

+8

Ben Von Handorf , , ItemsControl, ItemsPanel. :

<ListBox ItemsSource="{Binding MyCollection}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

ListBox , . WrapPanel, , "", ( span, html). WrapPanel . ( WrapPanel , , .)

. , ListBox. ListBox. , , .

+3

Source: https://habr.com/ru/post/1736495/


All Articles