如何在ItemsControl中添加占位项?ListBox末尾加自定义项不修改数据源
问题2:不修改绑定的apples集合,在ListBox末尾添加“ADD NEW...”项
推荐两种MVVM友好的实现方式:
方法1:使用CompositeCollection合并集合与自定义项
直接在XAML中配置ItemsSource,无需修改后台集合:
<Grid> <ListBox Name="lbxFruits" Margin="0,0,70,52"> <ListBox.ItemsSource> <CompositeCollection> <!-- 绑定原apples集合 --> <CollectionContainer Collection="{Binding Apples, RelativeSource={RelativeSource AncestorType=Window}}"/> <!-- 自定义ADD NEW项 --> <ListBoxItem Content="ADD NEW..." Foreground="Blue" Cursor="Hand"/> </CompositeCollection> </ListBox.ItemsSource> <ListBox.ItemTemplate> <DataTemplate DataType="{x:Type local:Fruit}"> <!-- 修正原模板的绑定错误:直接绑定Fruit对象的属性,而非ElementName --> <StackPanel Orientation="vertical" Background="Green"> <Label>Hello</Label> <TextBlock Text="{Binding Price}" Width="14" /> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Button Content="Button" HorizontalAlignment="Left" Margin="690,404,0,0" VerticalAlignment="Top" Click="Button_Click"/> </Grid>
后台代码简化为仅维护apples集合:
private void RebuildList() { // 只需确保Apples集合正确赋值/更新,无需处理ADD项 lbxFruits.Items.Refresh(); } private ObservableCollection<Fruit> apples ; public ObservableCollection<Fruit> Apples { get => apples; set { if (value != apples) { apples = value; NotifyPropertyChanged(); } } }
方法2:修改ListBox模板,追加固定项
通过自定义ControlTemplate,在原列表项的ItemsPresenter后直接添加ADD项:
<ListBox Name="lbxFruits" Margin="0,0,70,52" ItemsSource="{Binding Apples}"> <ListBox.Template> <ControlTemplate TargetType="ListBox"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer> <StackPanel> <!-- 显示原集合的项 --> <ItemsPresenter/> <!-- 追加ADD NEW项 --> <ListBoxItem Content="ADD NEW..." Foreground="Blue" Cursor="Hand"/> </StackPanel> </ScrollViewer> </Border> </ControlTemplate> </ListBox.Template> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="vertical" Background="Green"> <Label>Hello</Label> <TextBlock Text="{Binding Price}" Width="14" /> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
此方法的ADD项会始终固定在列表滚动区域的底部,不影响原集合的绑定逻辑。
内容的提问来源于stack exchange,提问作者Dev
相关产品推荐
相关产品推荐

