How to get a WPF window's ClientSize? How to get a WPF window's ClientSize? wpf wpf

How to get a WPF window's ClientSize?


One way you could do it is to take the top most child element, cast this.Content to its type, and call .RenderSize on it, which will give you its size.

<Window x:Class="XML_Reader.Window1"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    Title="Window1" Height="400" Width="600" WindowStyle="SingleBorderWindow">    <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">    </Grid></Window>((Grid)this.Content).RenderSize.Height((Grid)this.Content).RenderSize.Width

edit:

as Trent said, ActualWidth and ActualHeight are also viable solutions. Basically easier methods of getting what I put above.


var h = ((Panel)Application.Current.MainWindow.Content).ActualHeight;var w = ((Panel)Application.Current.MainWindow.Content).ActualWidth;


One way to do it is with the code below. XAML:

<Window x:Class="WpfApplication1.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApplication1"Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">    <Canvas>    </Canvas></Window>

C#:

using System.Windows;using System.IO;using System.Xml;using System.Windows.Controls;namespace WpfApplication1{    /// <summary>    /// Interaction logic for Window1.xaml    /// </summary>    public partial class Window1 : Window    {        public Window1()        {            InitializeComponent();        }        private void Window_Loaded(object sender, RoutedEventArgs e)        {            double dWidth = -1;            double dHeight = -1;            FrameworkElement pnlClient = this.Content as FrameworkElement;            if (pnlClient != null)            {                dWidth = pnlClient.ActualWidth;                dHeight = pnlClient.ActualHeight;            }        }    }}