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

时间:2022-03-07 07:21:43

I have the following XAML:

我有以下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>

I want to add content to wrapPanel1 - I tried the following code:

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

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

For some reason, the items don't show up. How can I fix that problem?

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

1 个解决方案

#1


4  

You should to use some ItemsControl, then add/remove the items from the item source property. You can use the ItemsPanel property or changing the template. For instance, using a ListBox and setting the Template property:

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

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

Now when you add or remove items from the Items property in your ViewModel/DataContext the item will be showed using the WrapPanel, and not the StackPanel that is the ListBox's default.

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

Hope this helps...

希望这可以帮助...

#1


4  

You should to use some ItemsControl, then add/remove the items from the item source property. You can use the ItemsPanel property or changing the template. For instance, using a ListBox and setting the Template property:

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

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

Now when you add or remove items from the Items property in your ViewModel/DataContext the item will be showed using the WrapPanel, and not the StackPanel that is the ListBox's default.

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

Hope this helps...

希望这可以帮助...