views:

399

answers:

1

Hello,

I've placed in my MainWindow a StackPanel, which gets dynamically on runtime new UserControls (the UserControl is a row of TextBoxes and a button named "Delete"). This is about how I create the UserControls:

PersonObject p = new PersonObject;
List.Add(p);

UserControlLine usrCtrlLine = new UserControlLine();
usrCtrlLine.DataContext = p;

StackPanel.Children.Add(usrCtrlLine);

Now the UserControl contains Textboxes like this:
TextBox TextWrapping="Wrap" Grid.Column="1" Text="{Binding Path=Firstname, Mode=TwoWay}"

My questions are, how can I let the UserControl
- Remove itself from the StackPanel ("get deleted")
- Delete the PersonObject p which is bound to it?

Thanks a lot!

A: 

I'm not sure I understand what you're trying to do here... You want to display a list of persons in the StackPanel ? You should use a ItemsControl, define its ItemsPanel as a StackPanel, and its ItemTemplate as a UserControlLine :

<ItemsControl ItemsSource="{Binding ListOfPersons}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel IsItemsHost="True"/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <my:UserControlLine/>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

To delete an item, you just remove it from the collection of persons, and the associated UserControlLine will also be removed from the ItemsControl (the collection should be an ObservableCollection)

Thomas Levesque
Thanks for this Input! I googled some more with your keywords and found nice examples here: http://www.galasoft.ch/mydotnet/articles/article-2007041201.aspx
Joseph Melettukunnel