最近涉及到一个横向显示CheckBox的功能,放在ListBox中进行遍历的话,在网络上找了好像很难做的样子,还用了模板,我尝试了一下,
前台代码
<ListBox Height="30" HorizontalAlignment="Left" Margin="231,25,0,0" Name="listMonth" VerticalAlignment="Top" Width="747" > <StackPanel x:Name="sp" Orientation="Horizontal"> </StackPanel> </ListBox>
后台动态添加CheckBox
foreach(var i in listOfMonth) { CheckBox cbMonth = new CheckBox(); cbMonth.Content = new TextBlock() { Text = i + "月?" }; cbMonth.IsChecked = true; cbMonth.Checked += new RoutedEventHandler(cbMonth_Checked); cbMonth.Unchecked += new RoutedEventHandler(cbMonth_Checked); this.sp.Children.Add(cbMonth); }
循环读取
foreach (var item in sp.Children) { if ((item as CheckBox).IsChecked ?? false) { int Month = Convert.ToInt32(((item as CheckBox).Content as TextBlock).Text.ToCharArray()[0].ToString()); } } 比较简单,不是吗。
您有更好的办法吗,交流一下。