如何在WrapPanel中动态添加项目?

4

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

出于某种原因,这些项目没有显示出来。我该如何解决这个问题?


3
不要在代码中操纵 UI 元素。使用 ItemsControl 代替,例如在 此答案 中所示。 - Clemens
也许可以看一下这个网址:https://dev59.com/5XHYa4cB1Zd3GeqPOral - Tsukasa
请从 MSDN 上的 Data Templating Overview 文章中获取更多信息。 - Clemens
你给我的链接对于我想在WrapPanel中放置不同的项没有帮助 - 它只适用于单个模板,包括适用于所有内容的数据类型。 - user3745785
1个回答

5

您应该使用一些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的默认设置。
希望这有所帮助...

所以如果我理解正确,我需要一个名为“Items”的属性,并使用以下代码添加项目:if (info.Attributes == FileAttributes.Directory) Items.Add(new FolderEntry(info.Name)); else Items.Add(new FileEntry(info.Name));但这也不起作用。 - user3745785
“Items”是一个属性,例如,您还需要检查具有“Items”属性的类是否是窗口的数据上下文(在这种情况下)... 您可能必须为项目定义数据模板。 - Raúl Otaño
据我所知,这个数据模板必须包含所有类型;我想添加不同类型的控件(FolderEntryFileEntry)。 - user3745785
然后,您应该为每个添加一个数据模板(没有键的数据模板和带有类型的数据模板,或使用数据模板选择器)。 - Raúl Otaño

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接