【问题标题】:Delete parent UserControl when child button is clicked单击子按钮时删除父用户控件
【发布时间】:2018-08-18 14:56:09
【问题描述】:

我在堆栈面板中添加了一个用户控件,并且该用户控件包含一个按钮。我试图在单击它的子按钮时删除该 UserControl。但它不起作用!
StackPanel

<StackPanel Name="StackPanelContainer" Grid.Row="3"> </StackPanel>

在 StackPanel 中添加控件

private void NewProducModule(object sender, RoutedEventArgs e)
{
    UserControl productModules = new AddProductModule();
    productModules.Name = "Product" + StackPanelContainer.Children.Count;
    StackPanelContainer.Children.Add(productModules);
}

UserControl的子按钮点击方式

private void DeleteSelfProduct(object sender, RoutedEventArgs e)
{
    FrameworkElement parent=(FrameworkElement)((Button)sender).Parent;
    NewInvoiceControl newInvoiceControl = new NewInvoiceControl();
    newInvoiceControl.StackPanelContainer.Children.Remove(parent);
}

【问题讨论】:

  • 您正在创建一个new NewInvoiceControl()。那肯定不是你想要操作的那个。无论如何,您的方法都被打破了。应该有一个视图模型,其中删除了数据项,然后删除了可视化它的 UI 元素。
  • NewInvoiceControl 是包含名为“StackPanelContainer”的 StackPanel 的主容器,然后我在 StackPanelContainer 中添加另一个名为“AddProductModule”的控件,并且此 AddProductModule 控件包含应该删除它的父级的按钮,它是动态创建的!
  • 但是如果你创建一个新的,它不是包含你的用户控件的那个。您必须访问 parent 的父级才能获取要删除子级的 StackPanel。
  • 不清楚为什么您需要访问 NewInvoiceControl。 ((Panel)parent.Parent).Children.Remove(parent) 应该可以工作。否则,请在代码中的某处保留对 NewInvoiceControl 的引用,即通过分配 x:Name
  • @RaoHammasHussain 在删除之前将控件的可见性设置为折叠,我认为这将有助于剩余空间。

标签: c# .net wpf xaml


【解决方案1】:

尝试从其子项中清除 StackPanel。 StackPanel 很好折叠。

private void DeleteSelfProduct(object sender, RoutedEventArgs e)
{ 
    StackPanelContainer.Children.Clear(); 
}

或者您可以从它的父级中删除 StackPanel。如果你认识父母。

private void DeleteSelfProduct(object sender, RoutedEventArgs e)
{ 
    var parent = (StackPanel)StackPanelContainer.Parent;

    parent.Children.Remove(StackPanelContainer); 
}

【讨论】:

    【解决方案2】:

    对于按钮中的操作,它缺少数据。 在命令参数中设置绑定到面板:
    CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}}}".

    在点击器中,从参数中提取面板并从中删除 UserControl。 假设“DeleteSelfProduct”方法位于 UserControl 背后的代码中的示例:

    private void DeleteSelfProduct(object sender, RoutedEventArgs e)
    {
        Button button = (Button)sender;
        if (button.CommandParameter is Panel panel)
            panel.Children.Remove(this);
    }
    

    P.S. 虽然这应该有所帮助,但我仍然建议您仔细查看 MVVM 模式中的典型 WPF 实现。 您不应该(如果正确实施)在 Sharp 代码中创建甚至简单地引用 WPF UI 元素。 您只需要在 Sharpe 上准备 WPF 所需的数据。 但它们的表示(包括动态创建、修改等)必须在 XAML 中完全定义。 XAML 是 WPF 的核心语言。 您需要探索它的所有功能:DataContext、Binding、DataTemplate、Style 等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多