如何将ObservableCollection<T>绑定到WrapPanel?

6

我正在使用WPF。我有一个ToggleButtonObservableCollection

private ObservableCollection<ToggleButton> myg = new ObservableCollection<ToggleButton>();

我希望你将这些ObservableCollection控件(ToggleButtons)绑定到WrapPanel的子元素。每当我使用myg.Add(new ToggleButton)时,都希望它自动将控件添加到WrapPanel中。

XAML示例:

<WrapPanel Name="test1">
    <!-- I want to bind (add) these controls here -->
</WrapPanel>

是否有可能实现,如果可以-如何实现?也许还有其他类似的方法可以做到这一点?


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - David Oesterreich
看起来是我想要的。但目前很难理解,我经验不足 :)。 - armandasalmd
也许还有其他的方法? - armandasalmd
1个回答

13

虽然很容易,但有一个小问题:

要利用“可观察集合(observable collection)”功能,需要将其绑定到对象,但是WrapPanel上没有ItemsSource等属性。

解决方法:

使用一个ItemsControl并将其面板设置为承载项的WrapPanel

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfApplication1"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="525"
        Height="350"
        mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <Button Grid.Row="0"
                Click="Button_Click"
                Content="Add toggle" />
        <ItemsControl Grid.Row="1" ItemsSource="{Binding}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</Window>

代码

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        private readonly ObservableCollection<ToggleButton> _collection;

        public MainWindow()
        {
            InitializeComponent();

            _collection = new ObservableCollection<ToggleButton>();

            DataContext = _collection;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var toggleButton = new ToggleButton
            {
                Content = "Toggle" + _collection.Count
            };
            _collection.Add(toggleButton);
        }
    }
}

注意:

将您的集合分配给DataContext可以使您不必直接处理WrapPanel<ItemsControl Grid.Row="1" ItemsSource="{Binding}">默认绑定到此属性。


1
易于理解的方式,它也能正常工作。干得好 :) - armandasalmd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接