I'm trying to add user controls to an ItemsControl dynamically with a button press. The user control has a view model associated with it. The UI is updating with the values that the view model is being instantiated with.
My property is defined as such:
private ObservableCollection<StageControlViewModel> _stages = new ObservableCollection<StageControlViewModel>();
public ObservableCollection<StageControlViewModel> Stages
{
get => _stages;
set => SetProperty(ref _stages, value);
}
I have the binding in the xaml setup with the following:
<ItemsControl ItemsSource="{Binding Stages}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type viewModels:StageControlViewModel}">
<views:StageControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I add it with this function:
private void AddStage()
{
StageControlViewModel viewModel = new StageControlViewModel
{
Name = ("Stage " (_stages.Count 1)),
TimeToNextStage = 106
};
Stages.Add(viewModel);
}
The user control's binding is setup with the following code:
<UserControl.DataContext>
<viewModels:StageControlViewModel/>
</UserControl.DataContext>
The view models inherit from ObservableObject.
Now the issue I have is that when I add the control the binding for the values aren't working. IE - Name and TimeToNextStage are not updating the UI. Not sure what I'm doing wrong here and help would be appreciated. Thanks in advance.
CodePudding user response:
Remove the DataContext assignment from the UserControl's XAML:
<UserControl.DataContext>
<viewModels:StageControlViewModel/>
</UserControl.DataContext>
When you write
<ItemsControl.ItemTemplate>
<DataTemplate>
<views:StageControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
the DataContext value of the StageControl is supposed to be inherited from the item container, a ContentPresenter which applies the DataTemplate. The inherited DataContext holds a reference to the associated element of the ItemsSource collection.
When you explicitly assign the UserControl's DataContext, the inheritance is broken and the control does not bind to an ItemsSource collection element.