1

在后面的代码中向网格中添加一列很容易:

col10 = new ColumnDefinition();
col10.SharedSizeGroup = "column1";

当您添加它添加到网格末尾的列时,例如您有一个包含 A 列和 B 列的网格,您使用上面的代码和一个新列 (C),并将其添加为 AB C。

可以这样设置吗?

出租车

而是将其添加到末尾?

谢谢

4

2 回答 2

3

ColumnDefinitions与任何其他 Collection 一样,并支持 IList<> 接口。所以只需使用插入方法来控制添加的顺序。

ColumnDefinition myColumn = new ColumnDefintion();
Grid myGrid = new Grid();
myGrid.ColumnDefinitions.Insert(0, myColumn);
于 2012-07-13T16:35:39.430 回答
1

试试这个:

XAML 文件:

<Window x:Class="DataGridAddColumn.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackPanel Orientation="Horizontal">
            <ComboBox Name="cbWhere" Width="100" VerticalAlignment="Center">
                <ComboBoxItem>Front</ComboBoxItem>
                <ComboBoxItem>End</ComboBoxItem>
            </ComboBox>

            <TextBlock Text="Name:" VerticalAlignment="Center" Margin="10,0,0,0" />
            <TextBox Name="tbName" MinWidth="100" VerticalAlignment="Center" />

            <Button Content="Create" VerticalAlignment="Center" Margin="10,0,0,0" Click="Button_Click" />

        </StackPanel>

        <DataGrid Grid.Row="1" Name="grid" />
    </Grid>
</Window>

代码隐藏:

using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DataGridAddColumn
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void AddColumn(DataGrid grid, string name, int where)
        {
            if (where == 0)
            {
                grid.Columns.Insert(0, new DataGridTextColumn{Header = name});
            }
            else
            {
                grid.Columns.Add(new DataGridTextColumn { Header = name });
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            AddColumn(grid, tbName.Text, cbWhere.SelectedIndex);
        }
    }
}
于 2012-07-13T16:43:35.180 回答