3

Hi im having an issue where a null Reference exception is being thrown in my xaml for a user control using a data template selector and I'm honestly not sure why. Here is the code below and any help would be appreciated.

UPDATE it only happens at design time not at run time

Data Template Selector code:

using System.Windows;
using System.Windows.Controls;
using UI.ViewModel;

namespace UI.DataTemplateSelectors
{
    public class CouponViewerDataTemplateSelector : DataTemplateSelector
    {
        public DataTemplate coupon1DataTemplateSelector { get; set; }
        public DataTemplate coupon2DataTemplateSelector { get; set; }
        public DataTemplate coupon3DataTemplateSelector { get; set; }



        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item == null)
                return null;
            var CouponViewerViewModel = (CouponViewerViewModel)item;
            switch (CouponViewerViewModel.Coupon.CouponBarcode )
            {

                case "994460":
                    return Coupon1DataTemplateSelector;
                case "994470":
                    return Coupon2DataTemplateSelector;
                case "994480":
                    return Coupon3DataTemplateSelector;


            }
            return null;
        }


    }
}

The Xaml (I have collapsed the different DataTemplates code as the xaml file is massive)

<UserControl x:Class="UI.View.CouponViewerView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:viewModel="clr-namespace:UI.ViewModel"
        xmlns:converter="clr-namespace:UI.View.Converter"
        xmlns:converters="clr-namespace:UI.Converters"
        xmlns:Web="clr-namespace:Web;assembly=Web"
        xmlns:dataTemplateSelectors="clr-namespace:UI.DataTemplateSelectors"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance Type=viewModel:CouponViewerViewModel, IsDesignTimeCreatable=True}"


        Height="1018" Width="720">
    <UserControl.Resources>
        <converter:EmptyStringToVisibilityConverter x:Key="EmptyStringToVisibilityConverter"/>
        <converters:AppendCharToBeginningAndEndOfStringConverter x:Key="AppendCharToBeginningAndEndOfStringConverter"/>
        <converters:HexToBackgroundColourConverter x:Key="HexToBackgroundColourConverter"/>
        <converters:HexToForegroundColourConverter x:Key="HexToForegroundColourConverter"/>
        <converters:MaxCharcterSelectionNameConverter x:Key="MaxCharcterSelectionNameConverter"/>
        <converters:DateTimeToSplitDataGridConverter x:Key="DateTimeToSplitDataGridConverter"/>
        <converters:HeaderFormatterConverter x:Key="HeaderFormatterConverter"/>

            <DataTemplate x:Key="Coupon1DataTemplateSelector" ...>

            <DataTemplate x:Key="Coupon2DataTemplateSelector" ...>

            <DataTemplate x:Key="Coupon3DataTemplateSelector" ...>

                 <dataTemplateSelectors:CouponViewerDataTemplateSelector

        Coupon1DataTemplateSelector="{StaticResource Coupon1DataTemplateSelector}"
        Coupon2DataTemplateSelector="{StaticResource Coupon2DataTemplateSelector}"
        Coupon3DataTemplateSelector ="{StaticResource Coupon3DataTemplateSelector}"
        x:Key="CouponViewerDataTemplateSelector" />

</UserControl.Resources>

 <StackPanel>
        <StackPanel x:Name="StackPanelToPrint">
            <StackPanel.ContextMenu >
                <ContextMenu>
                    <MenuItem Header="Print"  Click="PrintCurrentForm" />
                    <MenuItem Header="OverLay Image"  Command="{Binding Path=OverlayImageToCouponViewerCommand }" />
                </ContextMenu>
            </StackPanel.ContextMenu>

            <Grid Margin="0,0,0,0">

                <TextBlock Text="{Binding DesignTimeError}" Visibility="{Binding DesignTimeError, Converter={StaticResource EmptyStringToVisibilityConverter}}" Grid.ColumnSpan="2" Margin="0,0,0,34" />
                <Canvas Grid.ColumnSpan="2" Margin="0,0,0,0">
                    <Rectangle Fill="Black" Width="8.5" Height="8.5" Canvas.Left="11" Canvas.Top="128" />
                    <Rectangle Fill="Black" Width="8.5" Height="8.5" Canvas.Left="742.5" Canvas.Top="128" />
                    <TextBlock Canvas.Left="338" FontSize="9" Foreground="Red" Canvas.Top="1046"  Text="{Binding Path=MarkSenseCoupon.CouponBarcode}" />
                    <TextBlock FontFamily="Free 3 Of 9"  Canvas.Left="24"  Canvas.Top="1026" FontSize="110" Height="15" Text="{Binding Path=Coupon.CouponBarcode,  Converter={StaticResource AppendCharToBeginningAndEndOfStringConverter}}"/>
                    <TextBlock Canvas.Left="409" FontSize="9" Foreground="Red"  Canvas.Top="1046" Text="{Binding Path=MarkSenseCoupon.CouponInstance}" />
                    <TextBlock FontFamily="Free 3 of 9" Canvas.Left="409" Canvas.Top="1026"  FontSize="110" Height="15" Text="{Binding Path=Coupon.CouponInstance,  Converter={StaticResource AppendCharToBeginningAndEndOfStringConverter}}"/>
                    <Rectangle Fill="Black" Width="8.5" Height="8.5" Canvas.Left="11.5" Canvas.Top="1043" />
                    <Rectangle Fill="Black" Width="8.5" Height="8.5" Canvas.Left="742.5" Canvas.Top="1043" />



                </Canvas>

                <Image Canvas.ZIndex="1" Source="{Binding Coupon.OverlayImage}"  Margin="0,-21,-76,108" Stretch="Fill" x:Name="PrintImageContextMenu" />




                <StackPanel Margin="-105,146,66,0" Height="900" VerticalAlignment="Top" >

                    <ContentControl Content="{Binding}"  ContentTemplateSelector="{StaticResource CouponViewerDataTemplateSelector}"  />


                </StackPanel>

            </Grid>
        </StackPanel>

    </StackPanel>

</UserControl>

Stack Trace:

    at UI.DataTemplateSelectors.CouponViewerDataTemplateSelector.SelectTemplate(Object item, DependencyObject container)
   at System.Windows.Controls.ContentPresenter.ChooseTemplate()
   at System.Windows.Controls.ContentPresenter.EnsureTemplate()
   at System.Windows.Controls.ContentPresenter.OnPreApplyTemplate()
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.UIElement.UpdateLayout()
philmckendry
  • 555
  • 6
  • 21
  • 1
    Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Albireo Nov 30 '15 at 14:15
  • So where is the exception thrown? – JeffRSon Nov 30 '15 at 14:20
  • Ill add the stack trace now to the question – philmckendry Nov 30 '15 at 14:29
  • Is this a "guess the line" game? BTW, have you checked in debugger which type item has? – JeffRSon Nov 30 '15 at 14:46
  • Yes I have checked and it will always be of type CouponViewerViewModel. The cast was in at the start to make sure of this. And if I knew which line it was on, I would obviously point to it and ask for opinions there but as I have been looking at this for over 3 hours and cannot figure out the line I am asking for a broader answer. If I do find out which line it happens on I will update answer immediately. The only thing that I have managed to figure out so far is that it only happens at design time not at run time. – philmckendry Nov 30 '15 at 14:52
  • Ok I have found the line which this error is occurring it is where the content control is added: `` The issue I have with it is that it was working until I added the Coupon3DataTemplateSelector. The xaml inside however is exactly the same as Coupon1DataTemplateSelector which makes me confused as to why this is occurring – philmckendry Nov 30 '15 at 15:10
  • 1
    Try to replace `case "994480"` by `default`. Also any information about designtime or runtime should be in the question itself. You may want to put a `MessageBox` inside the selector to debug designtime problems. – JeffRSon Nov 30 '15 at 15:46
  • The default made no difference and I have amended the question with the info between design time and run time. I will try the `MessageBox` now but does the `MessageBox` not only appear at runtime, so I am wondering at how you can use this to diagnose design time problems? – philmckendry Nov 30 '15 at 15:54
  • The MessageBox will appear if it is included in the code that is executed at design time. Just try it in your ViewModel's constructor. – JeffRSon Dec 04 '15 at 08:00

2 Answers2

1

My Colleague who had been working on this before me had added this line of code to the ViewModel without me noticing and this caused all the issues due to it returning before design time data had been loaded

    public CouponViewerViewModel()
    {

        if (DesignerProperties.IsInDesignMode == true)
        {
            return;
        }
        if (DesignerProperties.IsInDesignMode)
        {
            LoadDesignTimeData();
        }

    }

Apologies for a silly question in the end

philmckendry
  • 555
  • 6
  • 21
  • BTW, there's no point in comparing a bool with `true` or `false` - either use the bool as it stands or negate it. Tell that to your colleague... – JeffRSon Dec 04 '15 at 08:02
0

Property names are case sensitive.

public DataTemplate coupon1DataTemplateSelector { get; set; }

vs.

Coupon1DataTemplateSelector="{StaticResource Coupon1DataTemplateSelector}"
bob
  • 1
  • Apologies I had to alter my code to ask the question on here, in code they are both in the correct case and ive altered the question to reflect this – philmckendry Nov 30 '15 at 14:33