如何在WPF中删除用户控件中动态创建的Row?

时间:2014-06-20 03:46:50

标签: c# wpf xaml

我创建了一个用户控件。我在页面中动态创建此用户控件。我在该控件中有一个按钮,用于删除动态创建的行。我无法删除整个Row。 这是我的Xaml:

 <Grid Name="grid_usercontrolTypeofFixture" >
    <Grid.RowDefinitions >
        <RowDefinition Height="20*"/>
        <RowDefinition Height="35*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="35*" />
        <ColumnDefinition Width="50*" />            
        <ColumnDefinition Width="15*" />
        <ColumnDefinition Width="10*" />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0"  Grid.Column="0" Margin="10,5,5,5" Content="Select/Type Fixture Type:" />      

    <TextBox Grid.Row="0" Grid.Column="1" Margin="10,5,5,5" Text="" Name="txtAuto"/>
    <TextBox Grid.Row="0" Grid.Column="2" Margin="10,5,5,5" Text="" Name="txt_percentage"/>

    <Button Grid.Row="0" Grid.Column="3" Margin="10,5,5,5" x:Name="btn_removeRow" Content="" Click="btn_removeRow_Click">
        <Button.Background>
            <ImageBrush ImageSource="/Assets/Knob Cancel.png"></ImageBrush>
        </Button.Background>
    </Button>
 </Grid>

这是我的代码背后:

 public int count = 1;
 private void btn_addnew_Click(object sender, RoutedEventArgs e)
    {
        var myControl = new UserControlTypeofFixture() { Name = "TypeofFixture" };
        grid_typeFixture.RowDefinitions.Add(new RowDefinition());
        Grid.SetRow(myControl, count);
        grid_typeFixture.Margin = new Thickness(10, 10, 10, 10);
        grid_typeFixture.Children.Add(myControl);
        count++;
    }

  private void btn_removeRow_Click(object sender, RoutedEventArgs e)
    {

               ???            
    }

我还有一些其他代码可以删除所选行。但它不起作用。我怎样才能删除整行?

2 个答案:

答案 0 :(得分:1)

这是您移除usercontrolrowdefinition

的方法
private void btn_removeRow_Click(object sender, RoutedEventArgs e)
        {

            var myControl = sender as Button;
            int rowindex = (int)myControl.GetValue(Grid.RowProperty);

            foreach (UIElement control in grid_typeFixture.Children)
            {
                var usercontrol = control as UserControlTypeofFixture;
                if (usercontrol != null)
                {
                    int childrowindex = (int)usercontrol.GetValue(Grid.RowProperty);
                    if (childrowindex == rowindex)
                    {
                        grid_typeFixture.Children.Remove(control);
                        grid_typeFixture.RowDefinitions.RemoveAt(childrowindex);
                        break;
                    }
                }

            }

        }

答案 1 :(得分:0)

好的,然后尝试我提到的替代解决方案,即将特定的RowDefinition Height设置为0:与您的情况相关,它应该如下所示:

 private void btn_removeRow_Click(object sender, RoutedEventArgs e)
 {
    grid_typeFixture.RowDefinitions[2].Height = new GridLength(0);            
 }