#1,207 – Data Binding Can Fail Quietly in Production Code

By default, if there’s a problem in how you set up data binding in WPF, the user of the application will never see the binding errors. An exception occurs internally for the binding error, but the WPF application won’t crash or report the exception.

Let’s say that we have that we have an application the includes the following properties in an object that we bind to (i.e. the object that we set the DataContext of a window to). (Using SetProp from post #1,205).

        private string _yourText;
        public string YourText
            get { return _yourText; }
                if (SetProp(ref _yourText, value))

        private int _textLength;
        public int TextLength
            get { return string.IsNullOrWhiteSpace(_yourText) ? 0 : _yourText.Length; }

Now let’s say that we have the following XAML fragment (assume in a Window whose DataContext is set to a class containing the properties shown above).

        <TextBlock Text="Enter text:"/>
        <TextBox Grid.Column="1" Margin="10,0" Text="{Binding YourText, UpdateSourceTrigger=PropertyChanged}"/>

        <TextBlock Grid.Row="1" Margin="0,10" Text="Length:"/>
        <TextBlock Grid.Row="1" Grid.Column="1" Margin="0,10" Text="{Binding TextLenth}"/>

Note the error–we spelled the TextLength property incorrectly, so binding for this TextBlock will fail.

If we just build and run the application, we won’t get an exception and the application will run fine. It just won’t bind to TextLength.

If you run the application in the Visual Studio debugger and pay attention to the Output window, you’ll see the error reported there. But WPF swallows this error and the application runs fine.