Silverlight:如何在Grid行之间动态添加控件?

时间:2011-07-27 23:50:29

标签: silverlight

我正在开发一个复杂的表单应用程序。每一行的末尾都有一个加号按钮,应该在它下方添加一个新行。如果您想了解我正在实施的示例,请查看iTunes和智能播放列表编辑对话框。它使用查询和嵌套,这是我用来构建用户友好的查询生成器。关于我如何在彼此之下嵌套行(在几个空格中标记)以及在彼此之间的网格中添加行的任何提示?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用TreeView control

您可以将每一行表示为一个对象,将它们放入ObservableCollection中,然后将数据绑定到TreeView的项目源。每个行对象还有一个Children属性,其中包含其嵌套行对象的ObservableCollection。

class Row
{
    public ObservableCollection<Row> Children { get; set; }

    // ....
}

partial class MainPage
{
    public ObservableCollection<Row> Rows{ get; set; }

    public MainPage()
    {
        //Add your initial rows
        this.AddRow( new Row(...) );
        this.AddRow( new Row(...) );
        //...

        this.InitializeComponents();
    }

    public void AddRow(Row newRow, Row parentRow=null)
    {
        if( parentRow == null )
        {
            // Add new row to root of tree
            this.Rows.Add(newRow);
        }
        else
        {
            //Add new row as child of an existing row of tree
            parentRow.Children.Add(newRow);
        }
    }
}

<UserControl x:Class="MainPage" x:Name="mainPageUserControl">
    <TreeView ItemsSource="{Binding Rows, ElementName=mainPageUserControl}">
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <!-- Template the behaviour/look of your rows as needed -->
        </HierarchicalDataTemplate>
    </TreeView>
</UserControl>

要添加或删除新行,只需在Observable集合中添加/删除Row对象即可。绑定到ObservableCollection意味着如果添加/删除行,TreeView将自动更新

相关问题