devSpAttitude
devSpAttitude

Reputation: 11

Check The First Generated RadioButton in An ItemsControl Group

I want to check the first radiobutton of my list after the loading of my view.

Code

<ItemsControl HorizontalAlignment="Stretch"
                ItemsSource="{Binding ListEquipement}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <RadioButton Checked="RadioButton_Checked"
                            GroupName="Equipement"
                            Background="{Binding Background}"
                            Style="{StaticResource selectedButton}"
                            Command="{Binding DataContext.SelectEquipementCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
                            CommandParameter="{Binding}">
                <Binding Path="Text" />
            </RadioButton>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 1

Views: 112

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31576

On the RadioButton add a handler to the Loaded event:

<DataTemplate>
    <RadioButton Content="{Binding OpName}" 
                 GroupName="Selectables" 
                 Loaded="RBLoaded"/>
</DataTemplate>

Then in the code behind, create a property which is a boolean status which when the status suggests this is the first time, check the radiobox:

public bool HasBeenChecked { get; set; }

private void RBLoaded(object sender, RoutedEventArgs e)
{
    if (HasBeenChecked == false)
    {
        (sender as RadioButton).IsChecked = true;
        HasBeenChecked = true;
    }
}

Upvotes: 0

Mason
Mason

Reputation: 11

Does the data have a Boolean property which can be used to initiate the IsChecked status? If so I would bind IsChecked to that property.

Then in the ViewModel, set the first one to be true such as

ListEquipment[0].MyIsCheckedProperty = true;

Upvotes: 1

Related Questions