Hopefully this question isn't too general, but I have just started using WPF and I'm banging my head against this.
I am developing an application that uses dynamically created controls. However currently I can not figure out how to make the commands create and add more controls to the current window because the commands only work when created in the ViewModel which can not see the View. However I can't keep everything in the XAML because all controls except for a few initially empty stack panels are dynamic. I feel like I'm missing something easy here though.
So here I have the binding
<MenuItem Header="LabelMenuItem" Command="{Binding Path=SpawnLabel}"/>
And here I have the command
public ICommand SpawnLabel { get { return new DelegateCommand(OnSpawnLabel); } }
Delegate command works like a relay command as defined here.
public class DelegateCommand : ICommand
{
private readonly Action _command;
private readonly Func<bool> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public DelegateCommand(Action command, Func<bool> canExecute = null)
{
if (command == null)
throw new ArgumentNullException();
_canExecute = canExecute;
_command = command;
}
public void Execute(object parameter)
{
_command();
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
}
This works in the view Model but I can't figure out how on earth to make it work in the View (or talk to the view without breaking MVVM principles) so that I can actually change the UI using the current controls created in c#.
Currently when I do it I get a BindingExpression path error which makes sense but I can not figure out how to bind it to look for the command in the view.