如何在列表框末尾添加自定义文本,而不使用ItemsSource将其添加到apples集合?
e.g.
Listbox:
Listbox Item1-Apple
Listbox Item2-Apple
Listbox Item3-Apple.. Could be more or less Apple the last item should say "ADD NEW..."
Listbox Item4-ADD NEW...
XAML:
<Grid>
<ListBox Name="lbxFruits" Margin="0,0,70,52">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation = "vertical" Background="Green">
<Label>Hello</Label>
<TextBlock Text = "{Binding Price, ElementName=lbxFruits}" Width = "14" />
<TextBlock Text = "{Binding Name, ElementName=lbxFruits}" />
</StackPanel >
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Button" HorizontalAlignment="Left" Margin="690,404,0,0" VerticalAlignment="Top" Click="Button_Click"/>
</Grid>
C编号:
private void RebuildList()
{
ListBoxItem addItem = new ListBoxItem() { Content = "ADD NEW ..." };
lbxFruits.ItemsSource = apples;
}
private ObservableCollection<Fruit> apples ;
public ObservableCollection<Fruit> Apples
{
get
{
return this.apples;
}
set
{
if (value != this.apples)
{
this.apples = value;
NotifyPropertyChanged();
}
}
}
2条答案
按热度按时间ct2axkht1#
您可以使用
CollectionView
的占位符功能:它会自动处理占位符项的位置(例如将其固定在末尾或开头)。当遍历集合时,此占位符项不会出现,因此不会污染数据结构。最大的优点是,由于集中在集合视图上,因此不必修改现有的数据模型及其相关逻辑。
通过将
IEditableCollectionView.NewItemPlaceholderPosition
属性设置为NewItemPlaceholderPosition.AtBeginning
或NewItemPlaceholderPosition.AtEnd
,可以启用占位符项。实现IList
(例如ObservableCollection
)的公共集合由实现IEditableCollectionView
的ListCollectionView
表示。启用占位符特性后,基础源集合的集合视图现在将包含静态
CollectionView.PlaceholderItem
。然后,您可以为
CollectionView.NewItemPlaceholder
创建一个专用的DataTemplate
,其类型为object
(基础类型定义为internal
,因此.NET库的客户端代码无法访问)。然后,定制的
DataTemplateSelector
将标识此占位符项以返回适当的DataTemplate
。占位符项的
DataTemplate
包含一个Button
,它允许在单击时添加新项(使用ICommand
或事件处理程序)并显示占位符项的文本。水果模板选择器.cs
主窗口.xaml.cs
主窗口.xaml
xwbd5t1u2#
有几种方法可以实现这一点,我建议您为
Fruit
定义一个接口,并让ObservableCollection
包含一个实现该接口的类示例列表,如下所示:然后你只需要触发你的代码来添加一个新的
Apple
,或者通过对OnClick
事件做出React并确定它是否来自AddApple
类类型,或者通过向在AddApple
中实现的接口添加一个命令来运行add new apple代码,在Apple
类中添加一个命令来做其他事情(或者什么都不做)。事实上,您可以将该接口添加到
Fruit
类,因为我假设Apple
继承自它。例如,
然后,您可以为从
Fruit
继承的所有类型使用类似的代码。或者您只需:
将它放在集合中,保持代码与以前基本相同。