Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

22. WPF Binding > The Problem...

The Problem...

To get a sense of what the WPF binding mechanism does for you, let’s look at a simple example. Here’s a simple window that displays the actual width and height of the Border object in the top pane.

image

Without WPF binding, in order to change the values in the labels when the size of the window changes, you’ll need to update them in code. The Border doesn’t have a SizeChanged event, but the Window does, and we can update the values in a basic event handler.

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
 WidthLabel.Content = Box.ActualWidth.ToString();
 HeightLabel.Content = Box.ActualHeight.ToString();
}

Now, that’s not too tedious, but what about the TextLabel? Well, TextBox exposes a TextChanged event, and we can catch that to update the label. But there’s a problem: As soon as the application runs, it generates a null reference exception because TextChanged gets called when the TextBox is created, which happens before the label is created. So you need to check that the window’s loaded:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint