如何在WPF自定义控件中填充集合控件?

时间:2011-05-15 15:50:56

标签: wpf wpf-controls binding

我正在学习在WPF中创建自定义控件的细节。到目前为止我理解的概念:

  1. 代码定义了控件的行为。
  2. 模板定义了控件的外观和视觉方面。
  3. 您可以将模板的元素绑定到基础控件对象的属性。
  4. 如果模板有多个集合控件,例如StackPanels,那么如何绑定它们以便它们由底层集合填充?我的第一个倾向是利用每个DataContext的{​​{1}},但我无法使其发挥作用。我觉得我错过了一个可以解决这个问题的关键概念。

2 个答案:

答案 0 :(得分:7)

你想在这些StackPanels中做什么?面板用于安排物品。如果要显示项目集合,可能需要使用ItemsControl(或多种类型的ItemsControls之一)。 ItemsControl功能非常强大 - 您可以指定项目的显示方式以及显示它们的面板的显示方式。您甚至可以指定面板是StackPanel。例如,

    <ItemsControl ItemsSource="{Binding ElementName=root, Path=List1}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <!-- Template defines the panel -->
                <StackPanel IsItemsHost="True" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <!-- Template defines each item -->
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

然后你想绑定到一个项目列表,使用ItemsControl非常容易!在使用自定义控件的情况下,您可能希望在代码隐藏中公开控件本身的依赖项属性,然后绑定到XAML中的那些属性。例如,您可以为您拥有的各种列表创建依赖项属性:

        public static readonly DependencyProperty List1Property = DependencyProperty.Register(
        "List1",
        typeof(IList<string>),
        typeof(MyControl));

    public static readonly DependencyProperty List2Property = DependencyProperty.Register(
        "List2",
        typeof(IList<string>),
        typeof(MyControl));

然后你可以绑定ItemsControls的ItemsSource属性:

    <ItemsControl ItemsPanel="..." ItemsSource="{Binding ElementName=root, Path=List1}" />
    <ItemsControl ItemsPanel="..." ItemsSource="{Binding ElementName=root, Path=List2}" />

(在这种情况下,我假设自定义控件有一个x:Name =“root”)

我希望这有帮助!

答案 1 :(得分:2)

您无法直接绑定StackPanel的内容。它只是一个布局控件。

但是,您可以使用ListBox并将其ItemsPanel设置为StackPanel(或您需要的任何其他布局控件)。然后,您可以将ListBox的{​​{1}}设置为您想要的任何基础集合。