Silverlight: How to dynamically add controls between Grid rows?
I'm developing a complex forms application. Each row has a plus button at the end that SHOULD add a new row right below it. If you want an example of what I'm implementing, check out iTunes and the smart playlist edit dialog. It uses queries and nesting which is what I'm using to build a user-friendly query builder. Any tips on how I can nest rows (tabbed over a few spaces) under each othe开发者_C百科r and add rows to a grid between each other?
You could try using the TreeView control
You could represent each row as an object put them in an ObservableCollection and then data bind it to the TreeView's item source. Each row object would also have a Children property containing an ObservableCollection of its nested row objects.
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>
To add or remove a new row, you can simply add/remove a Row object from the Observable collection. Binding to an ObservableCollection means that the TreeView will automatically update itself if a Row is added/remove
精彩评论