在代码中添加列到网格很容易:
col10 = new ColumnDefinition();
col10.SharedSizeGroup = "column1";
当您添加列时,它会添加到网格的末尾,例如,您有一个包含A和B列的网格,您可以使用上面的代码和一个新列(C),并将其添加为AB C。
可以这样设置吗?
C A B
而是添加到最后它添加到前面?
由于
答案 0 :(得分:3)
ColumnDefinitions
与任何其他集合一样,并支持IList<>接口。
所以只需使用insert方法来控制添加的顺序。
ColumnDefinition myColumn = new ColumnDefintion();
Grid myGrid = new Grid();
myGrid.ColumnDefinitions.Insert(0, myColumn);
答案 1 :(得分: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);
}
}
}