Hello,
The reason SubItem can't be preselected is because of this code.
SelectedSubItem = new SubItem { SubItemName = "Sub Item 1.1" } // Preselect the first sub-item
Passing this declaration at initialization time actually creates a new object, not the memory address corresponding to the SubItems. Therefore, in order to be able to implement the functionality of pre-selected SubItem, you need to keep the memory address consistent.
mainItems[0].SelectedSubItem = mainItems[0].SubItems[0];
mainItems[1].SelectedSubItem = mainItems[1].SubItems[1];
In addition, for data in the Model layer, you need to implement the INotifyChanged method to enable the data to notify the view layer when it has changed.
public class MainItem : INotifyPropertyChanged
{
private string _mainItemName;
private ObservableCollection<SubItem> _subItems;
private SubItem _selectedSubItem;
public string MainItemName {
get => _mainItemName;
set
{
if (_mainItemName != value)
{
_mainItemName = value;
OnPropertyChanged(); // reports this property
}
}
}
public ObservableCollection<SubItem> SubItems {
get => _subItems;
set
{
if (_subItems != value)
{
_subItems = value;
OnPropertyChanged(); // reports this property
}
}
}
public SubItem SelectedSubItem {
get => _selectedSubItem;
set
{
if (_selectedSubItem != value)
{
_selectedSubItem = value;
OnPropertyChanged(); // reports this property
}
}
}
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public class SubItem : INotifyPropertyChanged
{
private string _subItemName;
public string SubItemName {
get => _subItemName;
set
{
if (_subItemName != value)
{
_subItemName = value;
OnPropertyChanged(); // reports this property
}
}
}
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.