-1

我有包含多个用户控件的 GroupBox,每个用户控件都有删除按钮,请指导我如何在单击删除按钮时删除用户控件

4

1 回答 1

2
<UserControl x:Class="WpfApplication1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  Height="60" Width="150">
<Grid>
    <Border BorderThickness="2" BorderBrush="Red" Background="Black">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>

            </Grid.RowDefinitions>
            <TextBlock Text="Abcd" Background="Red"/>
    <Button Content="Delete" Grid.Row="1" Click="Button_Click"/>
        </Grid>
    </Border>
</Grid>

  public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public Action Delete;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if(Delete!=null)
            Delete();
    }

}

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="clr-namespace:WpfApplication1"
    xmlns:local="clr-namespace:WpfApplication1"
    Width="1000" Height="1000"
    Title="MainWindow"   x:Name="abc">
<Grid>
    <GroupBox Header="Group">
        <GroupBox.Content>
            <Grid x:Name="LayoutRoot">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <local:UserControl1 x:Name="uc1"/>
                <local:UserControl1 x:Name="uc2" Grid.Row="1"/>
            </Grid>
        </GroupBox.Content>
    </GroupBox>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        uc2.Delete += OnDelete;
    }
    private void OnDelete()
    {
        LayoutRoot.Children.Remove(uc2);
    }
}

我希望这能帮到您。

于 2013-02-13T14:20:48.807 回答