I keep climbing the steep WPF hill! So I want to create a UI that allows the user to dynamically add a text box. To do this they would hit a button.
I\'ve managed
Follow these steps and you are done:
ItemsControl
and bind it's ItemsSource
to some collection (preferably ObservableCollection) in your ViewModel. ItemTemplate
for ItemsControl with TextBox in it.ICommand
in ViewModel and bind it to button.XAML:
ViewModel:
public class MainWindowViewModel : INotifyPropertyChanged
{
public ObservableCollection SomeCollection { get; set; }
public ICommand TestCommand { get; private set; }
public MainWindowViewModel()
{
SomeCollection = new ObservableCollection();
TestCommand = new RelayCommand
RelayCommand:
public class RelayCommand : ICommand
{
readonly Action _execute = null;
readonly Predicate _canExecute = null;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Predicate canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
}
Note - I assume you know how to plug View with your ViewModel by setting DataContext to make the binding magic to work.