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

red*_*man 2 wpf binding wpf-controls

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

  1. 代码定义了控件的行为.
  2. 模板定义了控件的外观和视觉方面.
  3. 您可以将模板的元素绑定到基础控件对象的属性.

如果模板有多个集合控件,例如StackPanels,如何绑定它们以便它们由底层集合填充?我的第一个倾向是利用DataContext每一个StackPanel,但我无法使它工作.我觉得我错过了一个可以解决这个问题的关键概念.

Mat*_*att 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>
Run Code Online (Sandbox Code Playgroud)

然后你想绑定到一个项目列表,使用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));
Run Code Online (Sandbox Code Playgroud)

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

    <ItemsControl ItemsPanel="..." ItemsSource="{Binding ElementName=root, Path=List1}" />
    <ItemsControl ItemsPanel="..." ItemsSource="{Binding ElementName=root, Path=List2}" />
Run Code Online (Sandbox Code Playgroud)

(在这种情况下,我假设自定义控件具有ax:Name ="root")

我希望这有帮助!