代码之家  ›  专栏  ›  技术社区  ›  Toran Billups

如何在WPF中动态添加明细行?

  •  3
  • Toran Billups  · 技术社区  · 16 年前

    我能想到的唯一一个例子是HTML——例如,如果您在其中动态添加一个包含细节(可编辑)的tr w/a colspan+div,然后单击上一个tr

    我试着摸索一下XAML,想看看是否有人能用这个古怪的请求为我指明正确的方向。

    1 回复  |  直到 16 年前
        1
  •  7
  •   Jonathan C Dickinson    16 年前

    这里有一些东西,不确定是否是您要找的:

    XAML:

    <Grid Name="_mainGrid">
        <Grid.ColumnDefinitions>
            <!-- Contains the button -->
            <ColumnDefinition Width="Auto"/>
            <!-- Contains the edit control -->
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <!-- So that we have the 'empty' space at the end -->
            <RowDefinition Height="*"/> 
        </Grid.RowDefinitions>
    </Grid>
    

    代码:

        public Window1()
        {
            InitializeComponent();
            CreateRow(); // Bootstrap
        }
    
        private void CreateRow()
        {
            RowDefinition newRow = new RowDefinition();
            newRow.Height = new GridLength(0, GridUnitType.Auto);
            _mainGrid.RowDefinitions.Insert(_mainGrid.RowDefinitions.Count - 1, newRow);
    
            int rowIndex = _mainGrid.RowDefinitions.Count - 2;
    
            UIElement editControl = CreateEditControl();
            Grid.SetRow(editControl, rowIndex);
            Grid.SetColumn(editControl, 1);
            Grid.SetRowSpan(editControl, 1);
            Grid.SetColumnSpan(editControl, 1); // Change this if you want.
            _mainGrid.Children.Add(editControl);
    
            Button addButton = new Button();
            addButton.Content = "Add";
            addButton.Click += new RoutedEventHandler(b_Click);
            Grid.SetRow(addButton, rowIndex);
            Grid.SetColumn(addButton, 0);
            _mainGrid.Children.Add(addButton);
            addButton.Tag = editControl;
    
        }
    
        void b_Click(object sender, RoutedEventArgs e)
        {
            CreateRow();
            Control button = (Control)sender;
            UIElement editControl = (UIElement)button.Tag;
            _mainGrid.Children.Remove(button);
            Grid.SetColumn(editControl, 0);
            Grid.SetColumnSpan(editControl, 2);
        }
    
        private UIElement CreateEditControl()
        {
            return new TextBox();
        }
    
    推荐文章