在后面的代码中绑定动态创建的控件 [英] Binding dynamically created control in code behind

查看:54
本文介绍了在后面的代码中绑定动态创建的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经动态创建了弹出窗口,这些弹出窗口是在运行时在后面的C#代码中创建的,里面充满了来自xaml的内容,并且很难将它们绑定到后面的代码中.现在,当创建它时,它会遍历xaml中的项目并为每个项目创建一个关联的复选框:

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

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

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?

推荐答案

看看MSDN文章如何:在代码中创建绑定.

您可以这样写:

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

这篇关于在后面的代码中绑定动态创建的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆