【发布时间】:2012-03-06 18:49:01
【问题描述】:
我已经动态创建了在运行时在 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>
我怎样才能在后面的代码中完成与上面类似的事情?
【问题讨论】:
标签: c# wpf data-binding