我有一个listview,想要使用某种控件动态地添加项目。例如
提供" pack1" " PACK2"是ListViewItems我希望有额外的(红色方块)控件,它始终可见并添加新的" pack"点击项目。 所以任务很标准。通常如何完成?
更新 CompositeCollection似乎是一个很好的解决方案。
答案 0 :(得分:1)
我用listview做了一个非常简单的布局。我在listview项目中添加了一个按钮,并在按钮之前监听单击以插入新对象。
public MainWindow()
{
InitializeComponent();
listViewtst.Items.Add("test");
listViewtst.Items.Add("test2");
Button btn = new Button();
btn.Content = "+";
btn.Click += Btn_Click;
listViewtst.Items.Add(btn);
}
private void Btn_Click(object sender, RoutedEventArgs e)
{
listViewtst.Items.Insert(listViewtst.Items.Count - 1, "added by the btn");
}
不确定这是否是最佳解决方案,但如果没有人向我展示更好的方法,我会这样做:)
其他解决方案:
背后的代码
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<MyObject> _windows = new ObservableCollection<MyObject>();
public MainWindow()
{
InitializeComponent();
Windows.Add(new MyObject { Title = "Collection Item 1" });
Windows.Add(new MyObject { Title = "Collection Item 2" });
}
private void Btn_Click(object sender, RoutedEventArgs e)
{
}
public ObservableCollection<MyObject> Windows
{
get { return _windows; }
set { _windows = value; }
}
private void button_Click(object sender, RoutedEventArgs e)
{
Windows.Add(new MyObject { Title = "From Btn" });
}
}
public class MyObject
{
public string Title { get; set; }
}
Xaml:
<Window x:Class="Move_To_Prd_Dev.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="246" Width="325" Name="UI">
<Window.Resources>
<CollectionViewSource Source="{Binding ElementName=UI, Path=Windows}" x:Key="YourMenuItems"/>
</Window.Resources>
<Grid DataContext="{Binding ElementName=UI}">
<ListBox x:Name="listTxt" HorizontalAlignment="Left" Height="163" Margin="10,29,0,0" VerticalAlignment="Top" Width="297">
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource YourMenuItems}}" />
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
</Grid>
这使用CompositeCollection将按钮控件添加到列表中(优点是按钮始终为Last)