Migrating to .Net 4: Null reference exceptions thrown when adding event in xaml

.net-4.0, c#, xaml

Solution

I think th problem is you are trying to add event handlers while you are in a style setter. This is forbidden (for obscure reasons)... You should use EventSetters instead

For example:

<Style x:Key="YourSyleName" TargetType="{x:Type CtrlType}">
    <EventSetter Event="PreviewMouseLeftButtonDown" Handler="dgClient_PreviewMouseLeftButtonDown"/>
    <EventSetter Event="Loaded" Handler="GridContent_Loaded"/>
</Style>

Problem

At my place of work we've recently been upgrading our codebase from .Net 3.5 to .Net 4 (C#). Most issues encountered have been solved however this one I can't figure out. We initialise controls and pages through a mix of xaml and code behind (based on developer preference), however one page is throwing NullReferenceException when opened. Here is a snippet of code that is (one of many controls) throwing. All the code throwing exceptions is inside a DataTemplate (I figured that might be relevant) ``` <TextBox x:Name="Values" Grid.Column="1" Grid.Row="0" Margin="5,2,5,2" Text="{Binding ElementName=Descriptions, Path=SelectedValue, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, Converter={StaticResource EmptyConverter}}" GotFocus="Column_GotFocus" MinWidth="100" CharacterCasing="Upper" Visibility="{Binding Path=IsValueVisible, Converter={StaticResource VisibilityConverter}}" /> ``` Now in this, the line throwing is: ``` GotFocus="Column_GotFocus" ``` Column_GotFocus is in the code behind file. A few more facts: we had no issues before the migration, the exception gets throws continuously, and there are three different events causing this issue. The three events throwing are: ``` GotFocus="Column_GotFocus" SelectionChanged="Descriptions_SelectionChanged" Click="Search_Click" ``` Removing these fixes our problem completely, but obviously causes functional problems with the software. Does anyone have any idea what could be causing these issues? EDIT: Sorry, to clarify: The event handler is never called, the xaml event handler adding (GotFocus="Column_GotFocus" for example) seems to be where the exception is thrown. The exception is: ``` System.NullReferenceException occurred Message=Object reference not set to an instance of an object. Source= <assembly/namespace> StackTrace: at <assembly/namespace>.<Class>.System.Windows.Markup.IStyleConnector.Connect(Int32 connectionId, Object target) in <XamlFilePath>:line 291 InnerException: ``` Edit 2: The method handler is: ``` private void Column_GotFocus(object sender, RoutedEventArgs e) { ContentPresenter columnContentPresenter =(DependencyObject)sender).FindParent<ContentPresenter>(); Column column = (Column)columnContentPresenter.Content; string message = string.Format("{0} ({1})", column.Name, column.Field); ModuleDescriptor.UpdateStatusBar(message); } ```

Original source