Saggio
Saggio

Reputation: 2274

Binding dynamically created control in code behind

I have dynamically created popups that get created at run-time in the C# code behind that is filled with content from the xaml and having difficulty on how to bind them in the code behind. Right now when it is created, it loops through the items in the xaml and creates an associated checkbox for each one:

ListView listView = new ListView();

        //Create ListViewItem for each answer
        foreach (Answer ans in Questions.DataUsedQuestion.AnswerOptions)
        {
            ListViewItem item = new ListViewItem();
            StackPanel panel = new StackPanel();
            CheckBox checkBox = new CheckBox();
            TextBlock text = new TextBlock();

            panel.Orientation = Orientation.Horizontal;
            checkBox.Margin = new Thickness(5, 0, 10, 2);
            text.Text = ans.DisplayValue;

            panel.Children.Add(checkBox);
            panel.Children.Add(text);

            item.Content = panel;

            listView.Items.Add(item);
        }

I have similar controls elsewhere in the application that are bound in the xaml like this:

<TreeView ItemsSource="{Binding Path=AnswerOptions}" Height="320" Padding="5,5,5,5" Background="Transparent">
<TreeView.ItemTemplate >
    <HierarchicalDataTemplate ItemsSource="{Binding Path=AnswerOptions}" 
                                DataType="{x:Type QSB:Answer}" >
        <StackPanel Orientation="Horizontal" Margin="0,2,0,2">

            <CheckBox IsChecked="{Binding Path=IsSelected}" >
            </CheckBox>
            <TextBlock Text="{Binding DisplayValue}" Margin="5,0,0,0" />
        </StackPanel>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

How can I accomplish something similar to the above in the code behind?

Upvotes: 1

Views: 5878

Answers (1)

Clemens
Clemens

Reputation: 128060

Take a look at the MSDN article How to: Create a Binding in Code.

You could write something like:

Binding binding = new Binding("IsSelected");
binding.Source = ans;
checkBox.SetBinding(CheckBox.IsCheckedProperty, binding);

binding = new Binding("DisplayValue");
binding.Source = ans;
text.SetBinding(TextBlock.TextProperty, binding);

Upvotes: 4

Related Questions