gpt4 book ai didi

c# - WPF 向绑定(bind)集合添加额外项

转载 作者:行者123 更新时间:2023-11-30 20:37:09 26 4
gpt4 key购买 nike

我有一个 ItemsControl,它有绑定(bind)的项目。正如您在屏幕截图中看到的那样,这些项目绑定(bind)到一个属性,我希望出现一个额外的项目,它的行为与其他项目完全不同。我怎样才能做到这一点(最好只使用 xaml)?

Screenshot for what I want

最佳答案

看看Composite Collection . WPF 示例 herehere .

根据评论,这里是第一个例子的示例代码

<ComboBox>
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem Content="All" />
<CollectionContainer Collection="{Binding Source={StaticResource AllBitsSource}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>

编辑 - MVVM

CollectionContainer 的问题在于它无法访问当前的 DataContext。 StaticResource解决了

xaml

<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication5"
Title="MainWindow" Height="300" Width="525" FontSize="25">

<StackPanel Name="stk">
<StackPanel.Resources>
<CollectionViewSource x:Key="cvsBooks" Source="{Binding Path=Books}" />
</StackPanel.Resources>

<ListBox>
<ListBox.ItemsSource>
<CompositeCollection>
<ListBoxItem>
<StackPanel>
<TextBlock Margin="5,0">Not tagged</TextBlock>
</StackPanel>
</ListBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource cvsBooks}}"/>
</CompositeCollection>
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<Button Content="Add" Click="Button_Click"/>
</StackPanel>
</Window>

C#

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel();
this.stk.DataContext = vm;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
//should be Command in MVVM, but this is just example to see that ObservableCollection works
var btn = sender as Button;
(btn.DataContext as ViewModel).Books.Add(new Book() { Name = "Book" + DateTime.Now.Second });
}

}

public class ViewModel
{
public ViewModel()
{
this.Books = new ObservableCollection<Book>();
this.Books.Add(new Book() { Name = "Book 1" });
this.Books.Add(new Book() { Name = "Book 2" });
this.Books.Add(new Book() { Name = "Book 3" });
}

public ObservableCollection<Book> Books { get; private set; }
}

public class Book
{
public string Name { get; set; }
}

关于c# - WPF 向绑定(bind)集合添加额外项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com