July 23, 2014

Implicit style breaks XAML editor

This one was tough. Visual Studio didn't want to let me edit my XAML files. It kept displaying error message box stating "Object reference not set to an instance of an object." All I wanted was to select StaticResource from dropdown menu.

I've narrowed the problem down to the following XAML code:

<Application x:Class="StaticResourceTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style x:Key="{x:Type Button}" TargetType="Button">
        </Style>
        <Style x:Key="SpecialButton" TargetType="Button">
        </Style>
        <DataTemplate x:Key="SomeTemplate">
            <Button Style="{StaticResource }" />
        </DataTemplate>
    </Application.Resources>
</Application>


My cursor was at the end of the StaticResource markup and I've been looking at this dropdown menu:




Notice the empty row in the dropdown. That empty row was there every time I've got that dreaded "Object reference not set to an instance of an object." message box.

The empty row actually corresponds to the implicit style, the one with x:Key="{x:Type Button}". This syntax tells WPF to use the style for all controls in the application. It's used like that in tons of examples around the Internet. Visual Studio XAML editor doesn't like it for some reason. Fortunately there was a simple solution by using different XAML syntax:

<Application x:Class="StaticResourceTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style TargetType="Button">
        </Style>
        <Style x:Key="SpecialButton" TargetType="Button">
        </Style>
        <DataTemplate x:Key="SomeTemplate">
            <Button Style="{StaticResource SpecialButton}" />
        </DataTemplate>
    </Application.Resources>
</Application>

Yes, just drop the x:Key attribute. The implicit style will continue to apply to all controls in the application while XAML editor will be happy to auto-complete static resource names. Problem is solved.

No comments:

Post a Comment