开发者

Getting ListBoxItems to behave like radio buttons

开发者 https://www.devze.com 2023-03-25 04:59 出处:网络
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 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 RadioButtons will have the same GroupName, only one will be checked at any time.

0

精彩评论

暂无评论...
验证码 换一张
取 消