David Danielewicz
David Danielewicz

Reputation: 13

Loading user controls dynamically based on list of strings (Without code behind)

I am working on a project where the user should be able to export the values of different custom objects.

I am trying to find a way to load a number of check boxes dynamically (i am thinking user controls) based on a list of property names (string). The user should then be able to check or uncheck the check boxes based on the values that should be exported.

The problem I have is that I cannot give the user controls check boxes custom names which would link to the values that should be exported.

Upvotes: 1

Views: 74

Answers (1)

Emperor Eto
Emperor Eto

Reputation: 3518

ListBox or ItemsControl (if you need more flexibility) are definitely the way to go. However, it's not going to be enough to just generate the CheckBoxes as you're also going to need a way to track whether they're selected, so you want to make some kind of Choice class and bind the properties of the CheckBox to those of your Choice class. Something like this:

    <ListBox ItemsSource="{Binding Choices}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Name}"
                          IsChecked="{Binding IsChosen}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

And the code-behind:

public class Choice
{
    public string Name { get; set; }
    public bool IsChosen { get; set; }
}

Where your Choices property is a List or IEnumerable of Choices.

Upvotes: 1

Related Questions