如何动态地将项目添加到WrapPanel?

时间:2014-06-16 17:18:31

标签: c# wpf

我有以下XAML:

<Window x:Class="ImageComparing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="350" Width="525" xmlns:my="clr-namespace:ImageComparing" Title="Image comparing">
    <DockPanel>
        <ToolBar Name="toolbar1" DockPanel.Dock="Top" Height="41" Background="#FFA5D95A">
            /*other content*/
        </ToolBar>
        <WrapPanel Name="wrapPanel1" >
            /*other content*/
            <Label Content="Label" Height="28" Name="label1" />
        </WrapPanel>
    </DockPanel>
</Window>

我想将内容添加到wrapPanel1 - 我尝试了以下代码:

if (info.Attributes == FileAttributes.Directory)
    wrapPanel1.Children.Add(new FolderEntry(info.Name));
else
    wrapPanel1.Children.Add(new FileEntry(info.Name));

出于某种原因,这些物品不会出现。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

您应该使用一些ItemsControl,然后在项目来源属性中添加/删除项目。您可以使用ItemsPanel属性或更改模板。例如,使用ListBox并设置Template属性:

<ListBox Grid.Row="2" ItemsSource="{Binding Items}">
        <ListBox.Template>
            <ControlTemplate>
                <WrapPanel IsItemsHost="True"/>
            </ControlTemplate>
        </ListBox.Template>
    </ListBox>

现在,当您在ViewModel / DataContext中的Items属性中添加或删除项目时,将使用WrapPanel显示该项目,而不是StackPanel ListBox。默认设置。

希望这会有所帮助......

相关问题