Hi,
I am new in WPF and trying to add textboxes on button click with ViewModel. I am able to add the textboxes but not able to fetch the data.
What I have tried:
I have tried these..
XML
<Button Click="Button_Click" Content="sss" VerticalAlignment="Top" ></Button>
<StackPanel Margin="0,50,0,0">
<Button Content="Add TextBox" Command="{Binding TestCommand}"/>
<ItemsControl ItemsSource="{Binding SomeCollection, UpdateSourceTrigger= PropertyChanged, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=.}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
CodeBehind
public Window3ViewModel window3 = new Window3ViewModel();
public Window3()
{
InitializeComponent();
DataContext = window3;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var list = window3.SomeCollection.ToList();
}
ViewModel
public class Window3ViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> SomeCollection { get; set; }
public ICommand TestCommand { get; private set; }
public string Value { get; set; }
public Window3ViewModel()
{
SomeCollection = new ObservableCollection<string>();
TestCommand = new RelayCommand<object>(CommandMethod);
}
private void CommandMethod(object parameter)
{
SomeCollection.Add("");
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class RelayCommand<T> : ICommand
{
readonly Action<T> _execute = null;
readonly Predicate<T> _canExecute = null;
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
public RelayCommand(Action<T> execute, Predicate<T> 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);
}
}