I have a ToggleButton inside of a ListBox and when that button is clicked I want every other item in the ListBox to be unchecked.
i'm currently trying this
private void ToggleButton_Click(object sender, RoutedEventArgs e)
{
spriteToggleButton _tb = sender as ToggleButton;
for (int i = 0; i < aListBox.Items.Count; i++)
{
ListBoxItem lbi = (ListBoxItem)aListBox.Items[i]; // invalid cast exception here
lbi.IsSelected = false;
}
_tb.IsChecked = true;
}
开发者_如何学运维
but I am getting an invalid cast exception.
I would have thought that aListBox.Items[i] would return a ListBoxItem object.
Use a DataTemplate
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton IsChecked="{Binding SomeProperty}" GroupName="someName" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Since all RadioButton
s will have the same GroupName
, only one will be checked at any time.
精彩评论