After extensive researching I have not found an answer to this problem. I have a list box whose ItemsSource is a collection of Button objects. When I add a button to the collection it appears properly but when clicked the command is not executed. I have already implemented RelayCommand and it is used throughout my code.
C# MVVM WPF
The View
<ListBox ItemsSource="{Binding Buttons}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ListBox.ItemTemplate> <DataTemplate> <Button Margin="5,5,5,5" Content="{Binding Content}" Command="{Binding ExecuteButtonCommand}" CommandParameter="{Binding CommandParameter}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> The ViewModel
public RelayCommand _executeButtonCommand; public ICommand ExecuteButtonCommand { get { if (_executeButtonCommand == null) _executeButtonCommand = new RelayCommand(exec => this.ButtonCommands(param)); return _executeButtonCommand; } } For Testing I have this code.
public void AddButtons() { Buttons= new ObservableCollection<Button>(); Button btn = new Button(); btn.Content = "Generate Files"; btn.Command = "{Binding ExecuteButtonCommand}"; btn.CommandParameter = "Files"; Buttons.Add(btn); } But I cannot assign the Command that way. The rest of the button works correctly. So I put the Command= in the view as you see above.
If this has been answered, then I can't find it. The nearest answer is nine years old and does not work.
Thanks for looking.