[英]How to add a “Remove” button to each item of a ListBox and implement its functionality?
我需要一个“删除”按钮,用于UserControl列表框中的每个项目。 我正在尝试使用列表框模板。
<UserControl.Resources>
<DataTemplate x:Key="ListBoxItemTemplate">
<Grid>
<TextBlock x:Name="TB" Height="23" Text="" VerticalAlignment="Top" />
<Button Margin="500,0,0,0" Width="80" Click="Button_Click">remove</Button>
</Grid>
</DataTemplate>
</UserControl.Resources>
<ListBox x:Name="listbox" ItemTemplate="{StaticResource ListBoxItemTemplate}" SelectionChanged="ListBox_SelectionChanged"/>
如何使后端代码指定的每个项目的文本内容如下所示,并且“删除”按钮如何删除其对应的项目? 谢谢。
listbox.Items.Add("111");
listbox.Items.Add("222");
最简单的解决方案是使用WPF的ICommand系统。 使用此功能,可以将当前项目绑定到commands参数,并在代码beind中使用它。
(我使用的是窗口,而不是用户控件,但您可以更改它。
这是WPF :
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" x:Name="Window" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="ListBoxItemTemplate">
<Grid>
<TextBlock Height="23" Text="{Binding}" VerticalAlignment="Top" />
<Button Margin="500,0,0,0" Width="80" CommandParameter="{Binding}" Command="{Binding ElementName=Window, Path=OnClickCommand}">remove</Button>
</Grid>
</DataTemplate>
</Window.Resources>
<ListBox x:Name="listbox" ItemTemplate="{StaticResource ListBoxItemTemplate}" />
</Window>
{Binding}
表示绑定模板所使用的当前对象(在本例中为实现中的字符串)。
OnClickCommand
是什么。
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
listbox.Items.Add("asdf");
listbox.Items.Add("fdsfsadf");
listbox.Items.Add("dfsd");
listbox.Items.Add("a sdfas");
listbox.Items.Add("asdgas g");
//This is the command that gets executed.
OnClickCommand = new ActionCommand(x => listbox.Items.Remove(x));
}
public ICommand OnClickCommand { get; set; }
}
//This implementation of ICommand executes an action.
public class ActionCommand : ICommand
{
private readonly Action<object> Action;
private readonly Predicate<object> Predicate;
public ActionCommand(Action<object> action) : this(action, x => true)
{
}
public ActionCommand(Action<object> action, Predicate<object> predicate)
{
Action = action;
Predicate = predicate;
}
public bool CanExecute(object parameter)
{
return Predicate(parameter);
}
public void Execute(object parameter)
{
Action(parameter);
}
//These lines are here to tie into WPF-s Can execute changed pipeline. Don't worry about it.
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
}
请注意,使用字符串还是任何其他类型的对象都没有关系,因为{Binding}
获取ListBox.Items
列表中的当前对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.