简体   繁体   中英

Resize columns to fits DataGrid in WPF dynamically

I have code where I add custom DataGrid object in a Grid column dynamically like:

DataGrid dg = new DataGrid();
var vm = new MyViewModel();
dg.DataContext = vm;
dg.ItemsSource = vm.Items;

dg.VerticalAlignment = VerticalAlignment.Stretch;
dg.HorizontalAlignment = HorizontalAlignment.Stretch;

dg.AutoGenerateColumns = false;
dg.CanUserAddRows = false;
dg.CanUserResizeColumns = true;

dg.Columns.Clear();

dg.Columns.Add(new DataGridTextColumn
{
                Header = "Name",
                Binding = new Binding(nameof(DataItem.Path)) { Converter = new PathToNameConverter() },
                //Width = DataGridLength.Auto
});
...

// here add column definition to Grid
var gridColDefs = new ColumnDefinition();
gridColDefs.Width = GridLength.Auto;
gridColDefs.MinWidth = 500;

gridElement.ColumnDefinitions.Add(gridColDefs);
Grid.SetColumn(dg, gridElement.ColumnDefinitions.Count - 1);
gridElement.Children.Add(dg);

// populate datagrid items (I use Items => ObservableCollection<>)
await vm.FetchItemsAsync();

var star = new DataGridLength(1, DataGridLengthUnitType.Star);
dg.ColumnWidth = star;
foreach (var col in dg.Columns)
{
    col.Width = star;
}

dg.SelectionMode = DataGridSelectionMode.Extended;

After populating items in DataGrid , the columns are not filled to entire DataGrid width, a space remains as in picture:

在此处输入图片说明

What I want is to fill all columns to its DataGrid space ... I don't know where's my mistake

UPDATE

Items = new ObservableCollection<DataItem>();

public override Task FetchItemsAsync(string path = null)
{
            if (string.IsNullOrWhiteSpace(path))
            {
                return Task.Run(() =>
                {
                    var mainDrive = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
                    App.Current.Dispatcher.Invoke(() => Items.Clear());

                    var folders = Directory.GetDirectories(mainDrive);
                    var files = Directory.GetFiles(mainDrive);

                    foreach (var item in folders.Union(files))
                    {
                        var isDir = FolderUtility.IsFolder(item);
                        FileSystemInfo fs = null;
                        if (isDir)
                        {
                            fs = new DirectoryInfo(item);
                        }
                        else
                        {
                            fs = new FileInfo(item);
                        }

                        App.Current.Dispatcher.Invoke(() =>
                        {
                            try
                            {
                                Items.Add(new DataItem
                                {
                                    Path = item,
                                    Size = isDir ? FolderUtility.GetFolderSize(item) : new FileInfo(item).Length,
                                    LastModifiedDate = fs.LastWriteTimeUtc,
                                    CreationDate = fs.CreationTimeUtc
                                });
                            }
                            catch { }
                            finally { }
                        });
                    }
                });
            }

            return null;
}

** UPDATE 2 ** If I use

Width = new DataGridLength(1, DataGridLengthUnitType.Star)

for every column, after await statement, I got:

在此处输入图片说明

The XAML:

<Window ...>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <DockPanel x:Name="AppContentPanel" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto">
        <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <Grid>
                <Grid.ColumnDefinitions/>
            </Grid>
        </ScrollViewer>
    </DockPanel>
</Grid>

If you want the columns to divide the DataGrid equally, you could set the Width property of them to "*":

Width = new DataGridLength(1, DataGridLengthUnitType.Star);

Edit:

You also need to remove the gridColDefs.Width = GridLength.Auto; and set the HorizontalScrollBarVisibility property of the ScrollViewer to Disabled for the DataGrid to stretch as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM