在后面的代码中绑定动态创建的控件

时间:2012-03-06 18:49:01

标签: c# wpf data-binding

我动态创建了弹出窗口,这些弹出窗口在C#代码后面的运行时创建,其中填充了来自xaml的内容,并且难以在后面的代码中绑定它们。现在,当它被创建时,它会遍历xaml中的项目并为每个项目创建一个相关的复选框:

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);
        }

我在应用程序的其他地方有类似的控件,这些控件绑定在xaml中,如下所示:

<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>

如何在后面的代码中完成与上述相似的内容?

1 个答案:

答案 0 :(得分:4)

查看MSDN文章How to: Create a Binding in Code

你可以这样写:

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);