I've been learning about WPF and the MVVM pattern recently. I understand how the MVVM pattern works, but I'm struggling with this particular issue. On runtime, I'm trying to create multiple Buttons with Images as their content (using a Style), and then add these Buttons to a StackPanel which is then added to ContentControl within ItemsControl. All of the data is properly binded and the buttons are created, however, only one of the Buttons has the Image, all the rest are blank.
Here is all the code I used to get this.
Model:
public class DynamicButtonsModel
{
public StackPanel StackPanel { get; set; } = new StackPanel();
public DynamicButtonsModel()
{
for (int i = 0; i <= 20; i++)
{
StackPanel.Children.Add(new Button() { Height = 25, Width = 25, Style = Application.Current.FindResource("MenuControlButton") as Style });
}
}
}
ViewModel:
public class RegistryViewModel : BaseViewModel
{
public ObservableCollection<DynamicButtonsModel> mDynamicButtons = new ObservableCollection<DynamicButtonsModel>();
public RegistryViewModel()
{
DynamicButtons = new ObservableCollection<DynamicButtonsModel>() { new DynamicButtonsModel() };
}
public ObservableCollection<DynamicButtonsModel> DynamicButtons
{
get { return mDynamicButtons; }
set
{
if (mDynamicButtons == value)
return;
mDynamicButtons = value;
OnPropertyChanged();
}
}
}
View:
<UserControl.DataContext>
<local:RegistryViewModel/>
</UserControl.DataContext>
<Grid>
<ItemsControl ItemsSource="{Binding DynamicButtons}" Foreground="White"
HorizontalAlignment="Center" VerticalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding StackPanel}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Style:
<Style TargetType="{x:Type Button}" x:Key="MenuControlButton">
<Style.Setters>
<Setter Property="Content">
<Setter.Value>
<Image Source="/Assets/Menu/Expand.png"/>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
I'm not sure why it's not displaying all of them, but here is a preview with the background color changed so it's more visible.
Thank you and I hope you can help me with this very interesting problem!