让WPF UserControl删除自己和绑定到它的Data-Object?

时间:2009-06-17 08:33:18

标签: c# wpf user-controls

我在我的MainWindow中放置了一个StackPanel,它在运行时动态获取新的UserControls(UserControl是一行TextBoxes和一个名为“Delete”的按钮)。 这是关于我如何创建UserControls:

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

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

StackPanel.Children.Add(usrCtrlLine);

现在UserControl包含这样的文本框:
    TextBox TextWrapping =“Wrap”Grid.Column =“1”Text =“{Binding Path = Firstname,Mode = TwoWay}”

我的问题是,我怎么能让UserControl
- 从StackPanel中删除自己(“被删除”)
- 删除绑定到它的PersonObject p?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我不确定我理解你在这里要做什么......你想在StackPanel中显示一个人员列表?您应该使用ItemsControl,将其ItemsPanel定义为StackPanel,将其ItemTemplate定义为UserControlLine:

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

要删除项目,只需将其从人员集合中删除,相关的UserControlLine也将从ItemsControl中删除(该集合应为ObservableCollection)