我正在向 silverlight stackpanel 对象动态添加复选框,如下所示:
foreach (String userName in e.Result)
{
CheckBox ch = new CheckBox();
ch.Name = userName;
ch.Content = userName;
ContentStackPanel.Children.Add(ch);
}
我如何回读这些控件以检测它们中的哪些被选中。
我正在向 silverlight stackpanel 对象动态添加复选框,如下所示:
foreach (String userName in e.Result)
{
CheckBox ch = new CheckBox();
ch.Name = userName;
ch.Content = userName;
ContentStackPanel.Children.Add(ch);
}
我如何回读这些控件以检测它们中的哪些被选中。
您可以使用数据绑定到复选框列表。像这样的东西:
使用 Listbox 创建检查列表:
<ListBox x:Name="chkList" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<CheckBox Content="{Binding userName}" IsChecked="{Binding Checked, Mode=TwoWay}"></CheckBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
然后在您的代码中,只需使用您的对象将 chklist itemSource 设置为 ObservableCollection
chkList.ItemsSource = ....
您可能应该避免在这样的代码中创建复选框。可能对您有用的是复选框的迷你“ViewModel”。像这样的东西:
public class Option
{
public string Text {get; set;}
public bool IsChecked {get; set;}
}
然后,您可以像这样收集这些选项:
var options = new ObservableCollection<Option>();
填充后,您可以将 ObservableCollection 绑定到 ItemsControl:
<ItemsControl ItemsSource="{Binding options}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Text}" IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
该 XAML 将为您创建 CheckBoxes 为您添加到您的选项集合中的永远选项。真正伟大的是,您现在可以询问您的选项集合选择了哪些选项:
var selectedNames = from option in options
where option.IsChecked
select option.Text;
使用数据绑定和模板是您在 Silverlight/WPF 中应该熟悉的一种技术。这是一个非常重要的概念,它会让你在你的应用程序中做出惊人的事情。