我有GroupBox,其中包含多个usercontrol,每个用户控件都有删除按钮,当我点击删除按钮时,请指导我如何删除用户控件
答案 0 :(得分: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);
}
}
我希望这会对你有所帮助。