Skip to main content
 首页 » 编程设计

c#之在代码隐藏中绑定(bind)动态创建的控件

2024年02月23日21zengkefu

我动态创建了弹出窗口,这些弹出窗口是在运行时在 C# 代码中创建的,其中填充了来自 xaml 的内容,并且很难在如何在代码中绑定(bind)它们。现在,当它被创建时,它循环遍历 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); 
        } 

我在应用程序的其他地方有类似的控件,这些控件像这样绑定(bind)在 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 文章 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);