【问题标题】:How to bind an ObservableCollection<T> to a WrapPanel?如何将 ObservableCollection<T> 绑定到 WrapPanel?
【发布时间】:2016-04-12 20:41:28
【问题描述】:

我正在使用 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>

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

【问题讨论】:

标签: c# wpf data-binding observablecollection


【解决方案1】:

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

要利用“可观察集合”功能,需要绑定到它,但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,&lt;ItemsControl Grid.Row="1" ItemsSource="{Binding}"&gt; 默认绑定到此属性。

【讨论】:

  • 简单易懂的方式,它的工作原理。干得好:)
猜你喜欢
  • 2010-12-07
  • 2013-12-30
  • 1970-01-01
  • 2017-02-08
  • 2011-10-17
  • 2011-08-03
  • 2011-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多