The standard way in such cases is to create a wrapper, I use something like this, a universal one:
class Wrapper<T> : Vm { public T Value { get; } public Wrapper(T value) => Value = value; bool isChecked; public bool IsChecked { get => isChecked; set { if (Set(ref isChecked, value)) CheckedChanged?.Invoke(Value, IsChecked); } } public event Action<T, bool> CheckedChanged; }
For convenience, the event to which we subscribe is defined here.
So, let me have a VM class:
class TravelMethod : Vm { public string Name { get; } public TravelMethod(string name) => Name = name; }
and in the main VM a collection of objects of this class and a property for the selected element:
class MainVM : Vm { public ObservableCollection<TravelMethod> TravelMethods { get; } = new ObservableCollection<TravelMethod> { new TravelMethod("Walk"), new TravelMethod("Bicycle"), new TravelMethod("Car"), new TravelMethod("Train"), new TravelMethod("Plane") }; TravelMethod selectedTravelMethod; public TravelMethod SelectedTravelMethod { get => selectedTravelMethod; set => Set(ref selectedTravelMethod, value); }
Based on this collection, we need to generate a collection of wrappers, I do it in the constructor, you determine the right moment yourself - most likely it will be after loading data from the database:
public ObservableCollection<Wrapper<TravelMethod>> WrappedTravelMethods { get; } public MainVM() { WrappedTravelMethods = new ObservableCollection<Wrapper<TravelMethod>>( TravelMethods.Select(t => new Wrapper<TravelMethod>(t))); foreach (var wtm in WrappedTravelMethods) wtm.CheckedChanged += WtmCheckedChanged; } private void WtmCheckedChanged(TravelMethod travelMethod, bool isChecked) { if (isChecked) SelectedTravelMethod = travelMethod; } }
When setting the IsChecked flag, we set this selected item as the current one.
Now, in order to immediately set the first element as the selected one, you need to add a simple line in the constructor:
WrappedTravelMethods[0].IsChecked = true;
Markup for testing:
<Grid Margin="5"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <ItemsControl ItemsSource="{Binding WrappedTravelMethods}"> <ItemsControl.ItemTemplate> <DataTemplate> <RadioButton Content="{Binding Value.Name}" IsChecked="{Binding IsChecked}" GroupName="1"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <TextBlock Grid.Row="1" Text="{Binding SelectedTravelMethod.Name}"/> </Grid>

IsCheckedis not needed, why are you using it? - tym32167RequestWoodChangeteam? - VladDRequestWoodChangecommand isRequestWoodChange, I immediately get theWoodobject in the handler in the parameter, which is very convenient than getting the number, then look for it in the collection, etc. - Bretbas