Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在代码隐藏中绑定动态创建的控件_C#_Wpf_Data Binding - Fatal编程技术网

C# 在代码隐藏中绑定动态创建的控件

C# 在代码隐藏中绑定动态创建的控件,c#,wpf,data-binding,C#,Wpf,Data Binding,我已经动态创建了在运行时在C代码隐藏中创建的弹出窗口,其中充满了来自xaml的内容,并且很难在代码隐藏中绑定它们。现在,当它被创建时,它会循环遍历xaml中的项目,并为每个项目创建一个关联的复选框: ListView listView = new ListView(); //Create ListViewItem for each answer foreach (Answer ans in Questions.DataUsedQuestion.AnswerOpt

我已经动态创建了在运行时在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>

如何在代码隐藏中实现与上述类似的功能?

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

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

谢谢这正是我所需要的,只是我实际上不需要绑定复选框,因为每个复选框可以有多个实例,需要它们独立运行。谢谢!这正是我所需要的,只是我实际上不需要绑定复选框,因为每个复选框可以有多个实例,并且需要它们独立运行。