wpf get datagrid actual width and height beyond screen with scrollviewer

public double GetDatagridActualWidth(DataGrid dg)
{
    double totalWidth = 0;
    foreach(var col in dg.Columns)
    {
        totalWidth += col.ActualWidth;
    }
    return totalWidth;
}

public double GetDatagridActualHeight(DataGrid dg)
{
    double totalHeight = 0;

    foreach (var item in dg.Items)
    {
        var row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
        if (row == null)
        { 
            dg.UpdateLayout();
            dg.ScrollIntoView(item);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
        }

        if (row != null)
        {
            totalHeight += row.ActualHeight;
        }                   
    }
    return totalHeight;
}

image

 

 

 

 

 

//xaml
<Window x:Class="WpfApp14.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp14"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:DataGridPairConverter x:Key="DataGridPairConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <Button Command="{Binding SaveDataGridAsPicturesCommand}" Content="Save As Pictures">
                <Button.CommandParameter>
                    <MultiBinding Converter="{StaticResource DataGridPairConverter}">
                        <Binding ElementName="BooksDataGrid"/>
                        <Binding ElementName="StudentsDataGrid"/>
                    </MultiBinding>
                </Button.CommandParameter>
            </Button>
        </StackPanel>
        <TabControl Grid.Row="1">
            <TabItem Header="Books">
                <DataGrid x:Name="BooksDataGrid"
                          ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                          AutoGenerateColumns="True"
                          CanUserAddRows="False"
                          FontSize="30"/>
            </TabItem>

            <TabItem Header="Students">
                <DataGrid 
                    x:Name="StudentsDataGrid"
                    ItemsSource="{Binding StudentsCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                    AutoGenerateColumns="True"
                    CanUserAddRows="False"
                    FontSize="30"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>


//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp15
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext=this;
            InitData();
        }

        private void InitData()
        {
            BooksCollection=new ObservableCollection<Book>();
            for (int i = 0; i<1000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id=i+1,
                    Title=$"Title_{i+1}",
                    ISBN=$"{Guid.NewGuid().ToString("N")}",
                    Title2=$"Title2_{i+1}",
                    ISBN2=$"{Guid.NewGuid().ToString("N")}",
                    Title3=$"Title3_{i+1}",
                    ISBN3=$"{Guid.NewGuid().ToString("N")}"
                });
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = PropertyChanged;
            if (handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                booksCollection = value;
                OnPropertyChanged(nameof(booksCollection));
            }
        }

        public double GetDatagridActualWidth(DataGrid dg)
        {
            double totalWidth = 0;
            foreach(var col in dg.Columns)
            {
                totalWidth += col.ActualWidth;
            }
            return totalWidth;
        }

        public double GetDatagridActualHeight(DataGrid dg)
        {
            double totalHeight = 0;

            foreach (var item in dg.Items)
            {
                var row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
                if (row == null)
                { 
                    dg.UpdateLayout();
                    dg.ScrollIntoView(item);
                    row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
                }

                if (row != null)
                {
                    totalHeight += row.ActualHeight;
                }                   
            }
            return totalHeight;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            double actualWidth = GetDatagridActualWidth(BooksDataGrid);
            double actualHeight=GetDatagridActualHeight(BooksDataGrid);
            string msg = $"ActualWidth:{actualWidth}\n" +
                $"ActualHeight:{actualHeight}";
            MessageBox.Show(msg);
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string ISBN { get; set; }
        public string Title2 { get; set; }
        public string ISBN2 { get; set; }
        public string Title3 { get; set; }
        public string ISBN3 { get; set; }
    }
}

 

image

 

posted @ 2025-07-30 19:46  FredGrit  阅读(7)  评论(0)    收藏  举报