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

时间:2016-04-12 20:41:29

标签: c# wpf data-binding observablecollection

我正在使用WPF。我有ObservableCollection ToggleButton

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>
  

是否有可能,如果是 - 怎么样?也许还有其他类似的方法吗?

1 个答案:

答案 0 :(得分:6)

这很容易,但有一点点:

要利用'observable collection'功能,需要绑定它,但ItemsSource上没有WrapPanel等属性。

<强>解决方案:

使用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}">默认会绑定此属性。