我试图以编程方式查找所有复选框,以便查看是否已对其进行检查。下面的代码是xaml的样子,并且为列表中的每个项目创建了一个复选框。有谁知道我在代码中如何做到这一点?
<ScrollViewer Grid.ColumnSpan="5" Grid.Row="3" Height="350" Name="scrollViewer" >
<ItemsControl Name="lstTop10Picks">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="6" Name="gridTop11Stocks">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<CheckBox Style="{StaticResource CheckStyle}" Grid.Column="0" Grid.Row="3">
<CheckBox.RenderTransform>
<ScaleTransform ScaleX="0.5" ScaleY="0.5" />
</CheckBox.RenderTransform>
</CheckBox>
<TextBlock Style="{StaticResource NumberStyle}" Grid.Column="1" Grid.Row="3" Text="{Binding Id}" />
<TextBlock Style="{StaticResource SummaryStyle}" Grid.Column="2" Grid.Row="3" Text="{Binding Symbol}" HorizontalAlignment="Left" />
<TextBlock Style="{StaticResource SummaryStyle}" Grid.Column="3" Grid.Row="3" Text="{Binding Market}" />
<TextBlock Style="{StaticResource SummaryStyle}" Grid.Column="4" Grid.Row="3" Text="{Binding Return}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
var stocks = doc.Element(ns + "ArrayOfStockRating").Elements(ns + "StockRating")
.Select(n => new
{
Id = count += 1,
Symbol = n.Element(ns + "Symbol").Value,
Market = n.Element(ns + "Market").Value,
Return = n.Element(ns + "ShortRating").Value
})
.ToList();
lstTop10Picks.ItemsSource = stocks;
答案 0 :(得分:1)
更好的方法是在模型中添加属性以存储其状态(已选中/未选中):
public class MyModel
{
.....
.....
public bool? IsChecked { get; set; }
}
然后将CheckBox
绑定到上述属性:
<CheckBox IsChecked="{Binding IsChecked}"
Style="{StaticResource CheckStyle}" Grid.Column="0" Grid.Row="3">
<CheckBox.RenderTransform>
<ScaleTransform ScaleX="0.5" ScaleY="0.5" />
</CheckBox.RenderTransform>
</CheckBox>
通过这种方式,您不必为了从XAML中找到所有CheckBox
而弄乱您的代码,而是可以轻松地遍历您的模型并检查它的IsChecked
属性(甚至更好地使用LINQ)。
更新:
原来你在这里使用匿名类型,所以我们不需要类定义或部分类。只需更改LINQ Select()
部分即可提供IsChecked
属性,默认值设置为false
,例如:
.Select(n => new
{
Id = count += 1,
Symbol = n.Element(ns + "Symbol").Value,
Market = n.Element(ns + "Market").Value,
Return = n.Element(ns + "ShortRating").Value,
IsChecked = (bool?)false
})
然后您可以像以后一样遍历模型:
foreach(dynamic n in (IList)lstTop10Picks.ItemsSource)
{
bool? isChecked = n.IsChecked;
//do something with isChecked
}