一种方法是使用 a DataTemplate
on an ItemsControl
(就像你说的那样),DataTemplate
可以附加删除按钮以从ItemsControl
. 这只是一个简单的示例,您应该实现CommandBindings
而不是我添加的事件处理程序
示例代码在 c# 中,但它非常简单,我相信你可以很容易地转换它
xml:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="400" Name="UI" >
<Window.Resources>
<DataTemplate x:Key="itemTemplate" >
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtbx" Text="{Binding Value}" HorizontalAlignment="Left" Width="175" />
<Button Content="X" Width="{Binding ElementName=txtbx, Path=ActualHeight}" HorizontalAlignment="Right" Click="Button_Click" Tag="{Binding}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemTemplate="{StaticResource itemTemplate}" Name="itemsControl" ItemsSource="{Binding ElementName=UI, Path=Models}" Margin="0,40,0,0" />
<Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="3,8,0,0" Name="Button_Add" VerticalAlignment="Top" Width="75" Click="Button_Add_Click" />
</Grid>
</Window>
代码:
public partial class MainWindow : Window
{
private ObservableCollection<MyModel> _models = new ObservableCollection<MyModel>();
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<MyModel> Models
{
get { return _models; }
set { _models = value; }
}
private void Button_Add_Click(object sender, RoutedEventArgs e)
{
Models.Add(new MyModel());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Models.Remove((sender as Button).Tag as MyModel);
}
}
public class MyModel : INotifyPropertyChanged
{
private string _value;
public string Value
{
get { return _value; }
set { _value = value; NotifyPropertyChanged("Value"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}