I'm working on a little workout application and am running into an issue of displaying a view within another view.
I have a WorkoutSummaryView
with a backing WorkoutSummaryViewModel
. Within the workout summary view, I want to display the list of SingleExerciseView
items. Each SingleExerciseView
has a backing SingleExerciseViewModel
which displays the name and exercise and an ObservableCollection<Set>
ie Sets of exercises with a weight/reps pair.
Simplified Code:
public class ExerciseSummaryViewModel : ViewModelBase
{
public ExerciseSummaryViewModel()
{
_workout = DB.GetWorkout();
foreach (Exercise ex in _workout.Exercises)
ExerciseVMs.Add(new SingleExerciseViewModel(ex));
}
public ObservableCollection<SingleExerciseViewModel> ExerciseVms { get; private set; }
}
//Code for singleExerciseVM
public class SingleExerciseViewModel : ViewModelBase
{
public SingleExerciseViewModel(Exercise exercise)
{
Name = exercise.Name;
Sets = exercise.Sets;
开发者_StackOverflow中文版 }
public string Name { get; set; }
public ObservableCollection<Set> Sets { get; set; }
}
My problem is I'm not sure how to go from here to get my SingleExerciseViewModels to display. I did try setting the dataContext for the SingleExerciseView in xaml to my SEVM, but that's still not working.
//XAML for ExerciseSummaryView
<ListBox Height="496" Width="412" ItemsSource="{Binding ExerciseVms}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:SingleExerciseView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Your problem is that you're aggregating the SingleExerciseViewModels into a collection - but they are not attached to their views! That isn't going to work.
Each SingleExerciseViewModel needs to be attached to a SingleExerciseView. Then, each one of those views needs to be bound to a control on the ExerciseSummaryView that will display them (a ListView for example, because it can show custom user controls).
精彩评论