在MVVM上动态添加文本框 [英] Add textbox dynamically on MVVM
本文介绍了在MVVM上动态添加文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是WPF的新手,并尝试使用ViewModel按钮点击添加文本框。我可以添加文本框但无法获取数据。
我尝试过的事情:
我试过这些..
XML
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
CodeBehind
public Window3ViewModel window3 = new Window3ViewModel();
public Window3()
{
InitializeComponent();
DataContext = window3;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// list is containing list but content is blank
var list = window3.SomeCollection.ToList();
}
ViewModel
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);
}
}
推荐答案
使用ItemsControl
并将其绑定到ObservableCollection< Model>
。模型的属性绑定在ItemTemplate
。
因此,当您将模型添加到集合时,TextBoxes将自动生成并绑定到每个Model的属性。
Use anItemsControl
and bind it to anObservableCollection<Model>
. The Model's properties are bound in theItemTemplate
.
So as you add Models to the collection, the TextBoxes will auto-generate and bind to each Model's property.
这篇关于在MVVM上动态添加文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文