【问题标题】:Let WPF UserControl delete itself and Data-Object which is bound to it?让 WPF UserControl 删除自身和绑定的 Data-Object?
【发布时间】:2009-06-17 08:33:18
【问题描述】:

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

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?

非常感谢!

【问题讨论】:

    标签: c# wpf user-controls


    【解决方案1】:

    我不确定我是否理解您在此处尝试执行的操作...您想在 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)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多