WPF将特定按钮添加到ItemsControl ItemsPanel [英] WPF add specific button to ItemsControl ItemsPanel
问题描述
我有一个ItemsControl,可在其中显示一长串对象.我将其显示在包装面板中,因此用户无需滚动.现在,我想在列表末尾添加一个Button,以便用户可以添加新对象.最好的方法是什么?
I have an ItemsControl where I display a long list of objects. I display it in a wrappanel so the user does not need to scroll. Now i want to add a Button at the end of the list, so the user can add new objects. What would be the best way to do this?
这是我的xaml:
<ItemsControl ItemsSource="{Binding Inventory}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<Button Content="{Binding Name}"
MouseDoubleClick="CallEdit"/>
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel MaxHeight="{Binding ElementName=window, Path=Height}"
Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
推荐答案
我建议的一种方法是根据目的使用2个项目模板.
one way i can suggest is to have 2 item templates, depending on their purpose.
在这里我创建了一个类InventoryNewItem
,它是从InventoryItem
(public class InventoryNewItem : InventoryItem {}
,仅此而来)派生的.类型用作从资源中选择模板的关键
here I created a class InventoryNewItem
, derived from InventoryItem
(public class InventoryNewItem : InventoryItem {}
, that is all). Type is used as a key for template selection from resourses
<ItemsControl ItemsSource="{Binding Inventory}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type views:InventoryItem}">
<StackPanel>
<Grid >
<Button Content="{Binding Path=Name}" Click="ButtonBase_OnClick"/>
</Grid>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type views:InventoryNewItem}">
<StackPanel>
<Grid >
<Button Content="+" Background="Green" Click="Add_OnClick"/>
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel MaxHeight="{Binding ElementName=window, Path=Height}"
Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
优点:单独的模板和每个模板的单击处理程序(或命令绑定)
pros: separate templates and click handlers (or command bindings) for each template
缺点:将InventoryNewItem
保留在ItemsSource
中最后位置的其他操作(您不能添加,必须插入新元素)
cons: additional manipulations to keep InventoryNewItem
at the last position in ItemsSource
(you can't add, have to insert new elements)
我的测试ItemsSource
var list = Enumerable.Range(1, 20)
.Select(i => new InventoryItem {Name = i.ToString()})
.Concat(new List<InventoryItem> {new InventoryNewItem()});
ItemsSource = new ObservableCollection<InventoryItem>(list);
这篇关于WPF将特定按钮添加到ItemsControl ItemsPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!