How to edit items inside an observable collection from a view [duplicate]

1 day ago 5
ARTICLE AD BOX

In my application I am displaying items from an observable collection and I want the user to be able to edit them. Lots of threads here discuss how to add or remove items from a collection, but I couldn't find anything on how to edit them.

So I have the following collection in my view model:

private ObservableCollection<ExerciseModel> exercises = new(); public ObservableCollection<ExerciseModel> Exercises { get { return exercises; } set { exercises = value; OnPropertyChanged(); } }

ExerciseModel implements INotifyPropertyChange and puts initial value into items:

public class ExerciseModel: INotifyPropertyChanged { private static readonly int maxWeights = 5; public string IdExercise { get; set; } = string.Empty; public string IdExerciseSet { get; set; } = string.Empty; public string ExerciseName { get; set; } = string.Empty; public ObservableCollection<string> exerciseWeights = new(); public ObservableCollection<string> ExerciseWeights { get { return exerciseWeights; } set { exerciseWeights = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler? PropertyChanged; public void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public ExerciseModel() { for (int i = 0; i < maxWeights; i++) { ExerciseWeights.Add("10"); } } }

The part that is a little difficult to understand for me is this. I'm not really sure how to do the binding to TextBoxes. I did it like this (using Binding Path=. ):

<ItemsControl Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="7" Grid.RowSpan="5" VerticalAlignment="Top" ItemsSource="{Binding Exercises}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBox Width="75" Text="{Binding ExerciseName}"/> <ItemsControl ItemsSource="{Binding ExerciseWeights}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <TextBox Width="30" Text="{Binding Path=.}"/> <!-- Path=. Not really sure if this is the right way to bind --> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>

Such items control is displayed correctly. The default values are displayed, but when I change any of these values they don't get updated in my view model. What could be wrong here?

Read Entire Article