1

I've been googling this without getting the issue of that:

Simple xaml:

<Window x:Class="WpfHeightBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHeightBinding="clr-namespace:WpfHeightBinding"
        Title="MainWindow" 
        Width="{Binding Width}"
        Height="{Binding Height}"
        SizeToContent="Manual"
        >
    <Window.DataContext>
        <wpfHeightBinding:TheDataContext />
    </Window.DataContext>
    <Grid>
    </Grid>
</Window>

I bind both Width and Height to the data context. Here's the cs code

using System.Windows;

namespace WpfHeightBinding
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class TheDataContext
    {
        public int Width
        {
            get { return 200; }
        }

        public int Height
        {
            get { return 400; }
        }
    }
}

I set breakpoints to both getters. Only the first one is fetched, Height is ignored. If I switch Height and Width in xaml, then only the Height is fetched and Width is ignored.

I really cannot explain this behaviour. The window's height seems to be arbitrary. I have no MinHeight, nothing else influencing it, what happens to the binding? There is no error. SizeToContent has no effect.

I would understand if none of them are used as they might have been fetched before DataContext has been initialized but the DataContext is queried.

Samuel
  • 6,126
  • 35
  • 70
  • 2
    please check this link if it help http://stackoverflow.com/questions/2673600/problems-with-binding-to-window-height-and-width – Vinkal Feb 21 '15 at 19:24

1 Answers1

2

You need to give your 'Width' and 'Height' properties setters in code-behind - and then make your bindings 'TwoWay':

XAML

<Window x:Class="WpfHeightBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfHeightBinding="clr-namespace:WpfHeightBinding"
    Title="MainWindow" 
    Width="{Binding Width, Mode=TwoWay}"
    Height="{Binding Height, Mode=TwoWay}"
    SizeToContent="Manual"        
    >
<Window.DataContext>
    <wpfHeightBinding:TheDataContext />
</Window.DataContext>

Code-behind:

public class TheDataContext
{
    public int Width { get { return 800; } set { } }
    public int Height { get { return 200; } set { } }
}
James Harcourt
  • 6,017
  • 4
  • 22
  • 42
  • A possible alternate may be to use a `OneTime` binding... I'm not sure, I've never tested it. – Rachel Feb 26 '15 at 16:35