CalendarItem template causing NullReferenceExeption
-
Thursday, January 27, 2011 11:36 PM
I created my own calendar and datepicker control before they were released and am now mobing to .Net 4.0. I decided to go with the controls provided in WPF 4.0 but I am trying to create my own style for the calendar and not having much luck so far. I have created many styles for most controls provided and I like to open the default styles in Relfector and basically just modify them using it as a base. Unfortunately, the one provided for the Calendar control contained many errors when I copied it mainly due to VisualState tags but I figured they were optional and removed them, much like event or data triggers that change the visual appearance.
At first it seemed as though it worked but when I hovered the previous, next or header button it crashed giving a NullReferenceExeption. I figured it was due to removing the visual states and got a template from the net someone has used. Unfortunately, it was for the Calendar control in the WpfToolkit, but I made the modifications and the header button works. When I click it I get the Year view and again to get the Decade view. However, when I click to go to the month view or click the next/previous month view I get the a NullReferenceExeption. I have no idea what is causing the error as it is inside a framework DLL and consequently have no idea how to fix it. I tried to add VisualStates thinking it was trying to apply a visual state that I did not specify. I also tried opening the Calendar control code in Reflector to get an idea of what is causing the error. Here is my template so far:
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Calendar xmlns:vsm="clr-namespace:System.Windows;assembly=PresentationFramework"> <Calendar.CalendarItemStyle> <Style TargetType="CalendarItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="CalendarItem"> <ControlTemplate.Resources> <DataTemplate x:Key="DayTitleTemplate"> <TextBlock Text="{Binding}" HorizontalAlignment="Center" /> </DataTemplate> </ControlTemplate.Resources> <DockPanel Name="PART_Root" LastChildFill="True"> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name="CommonStates"> <vsm:VisualState x:Name="Normal" /> <vsm:VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Storyboard.TargetName="PART_DisabledVisual" Storyboard.TargetProperty="Opacity" To="1" Duration="0" /> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <Button x:Name="PART_PreviousButton" DockPanel.Dock="Left" Content="<" Focusable="False"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid Cursor="Hand"> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name="CommonStates"> <vsm:VisualState x:Name="Normal" /> <vsm:VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Storyboard.TargetName="TextColor" Storyboard.TargetProperty="Color" To="#FF73A9D8" Duration="0" /> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Storyboard.TargetName="TextColor" Storyboard.TargetProperty="Opacity" To=".5" Duration="0" /> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <Rectangle Fill="#11E5EBF1" Stretch="Fill" Opacity="1"/> <Grid> <Path Margin="14,-6,0,0" Height="10" Width="6" VerticalAlignment="Center" HorizontalAlignment="Left" Stretch="Fill" Data="M288.75,232.25 L288.75,240.625 L283,236.625 z"> <Path.Fill> <SolidColorBrush x:Name="TextColor" Color="#FF333333" /> </Path.Fill> </Path> </Grid> </Grid> </ControlTemplate> </Button.Template> </Button> <Button x:Name="PART_NextButton" DockPanel.Dock="Right" Content=">" Focusable="False"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid Cursor="Hand"> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name="CommonStates"> <vsm:VisualState x:Name="Normal" /> <vsm:VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Storyboard.TargetName="TextColor" Storyboard.TargetProperty="Color" To="#FF73A9D8" Duration="0" /> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Storyboard.TargetName="TextColor" Storyboard.TargetProperty="Opacity" To=".5" Duration="0" /> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <Rectangle Fill="#11E5EBF1" Stretch="Fill" Opacity="1"/> <Grid> <Path Margin="0,-6,14,0" Height="10" Width="6" VerticalAlignment="Center" HorizontalAlignment="Right" Stretch="Fill" Data="M282.875,231.875 L282.875,240.375 L288.625,236 z"> <Path.Fill> <SolidColorBrush x:Name="TextColor" Color="#FF333333" /> </Path.Fill> </Path> </Grid> </Grid> </ControlTemplate> </Button.Template> </Button> <Button x:Name="PART_HeaderButton" DockPanel.Dock="Top" FontWeight="Bold" Focusable="False"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid Cursor="Hand"> <vsm:VisualStateManager.VisualStateGroups> <vsm:VisualStateGroup x:Name="CommonStates"> <vsm:VisualState x:Name="Normal" /> <vsm:VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Storyboard.TargetName="TextColor" Storyboard.TargetProperty="Color" To="#FF73A9D8" Duration="0" /> </Storyboard> </vsm:VisualState> <vsm:VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Storyboard.TargetName="buttonContent" Storyboard.TargetProperty="Opacity" To=".5" Duration="0" /> </Storyboard> </vsm:VisualState> </vsm:VisualStateGroup> </vsm:VisualStateManager.VisualStateGroups> <ContentPresenter x:Name="buttonContent" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="1,4,1,9" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"> <TextElement.Foreground> <SolidColorBrush x:Name="TextColor" Color="#FF333333"/> </TextElement.Foreground> </ContentPresenter> </Grid> </ControlTemplate> </Button.Template> </Button> <Grid> <Grid x:Name="PART_MonthView" Visibility="Visible"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> </Grid> <Grid x:Name="PART_YearView" Visibility="Hidden"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> </Grid> </Grid> <Rectangle x:Name="PART_DisabledVisual" Opacity="0" Visibility="Collapsed" Fill="#A5FFFFFF"/> </DockPanel> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="PART_DisabledVisual" Property="Visibility" Value="Visible"></Setter> </Trigger> <DataTrigger Binding="{Binding Path=DisplayMode, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Calendar}}" Value="Year"> <Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden"></Setter> <Setter TargetName="PART_YearView" Property="Visibility" Value="Visible"></Setter> </DataTrigger> <DataTrigger Binding="{Binding Path=DisplayMode, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Calendar}}" Value="Decade"> <Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden"></Setter> <Setter TargetName="PART_YearView" Property="Visibility" Value="Visible"></Setter> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Calendar.CalendarItemStyle> </Calendar> </Grid> </Window>
On a side note, I really don't like VisualStates and if not specifying them is what is causing my exception I think that should be changed. I personally don't like setting the visual state from code when a dependency property with a trigger can do the job (ie. IsEnabled, MouseOver, Pressed). But it seems as though it will become a part of WPF and I think at least valid visual states should be specified somewhere similar to specifying template parts at the top of a control class. However, I will probably still refrain from using them :)
When I click the next button here is the exception detail:
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=PresentationCore
StackTrace:
at System.Windows.Automation.Peers.AutomationPeer.EnsureChildren()
at System.Windows.Automation.Peers.AutomationPeer.GetChildren()
at System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(AutomationPeer parent)
at System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(AutomationPeer parent)
at System.Windows.Automation.Peers.AutomationPeer.ValidateConnected(AutomationPeer connectedPeer)
at System.Windows.Automation.Peers.AutomationPeer.AutomationPeerFromInputElement(IInputElement focusedElement)
at System.Windows.Automation.Peers.AutomationPeer.RaiseFocusChangedEventHelper(IInputElement newFocus)
at System.Windows.Input.KeyboardDevice.ChangeFocus(DependencyObject focus, Int32 timestamp)
at System.Windows.Input.KeyboardDevice.TryChangeFocus(DependencyObject newFocus, IKeyboardInputProvider keyboardInputProvider, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
at System.Windows.Input.KeyboardDevice.Focus(DependencyObject focus, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
at System.Windows.Input.KeyboardDevice.Focus(IInputElement element)
at System.Windows.UIElement.Focus()
at System.Windows.Input.KeyboardNavigation.Navigate(DependencyObject currentElement, TraversalRequest request, ModifierKeys modifierKeys, DependencyObject firstElement)
at System.Windows.FrameworkElement.MoveFocus(TraversalRequest request)
at System.Windows.Controls.Primitives.CalendarItem.FocusDate(DateTime date)
at System.Windows.Controls.Calendar.MoveDisplayTo(Nullable`1 date)
at System.Windows.Controls.Calendar.OnNextClick()
at System.Windows.Controls.Primitives.CalendarItem.NextButton_Click(Object sender, RoutedEventArgs e)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at CalendarStyle.Application.Main() in D:\Users\Manuel\Documents\My Visual Studio Projects\Testing\CalendarStyle\CalendarStyle\obj\x86\Debug\Application.g.vb:line 64
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
If I can't get it working I will have to use my own controls instead but hopefully someone can help me to get it working.
All Replies
-
Monday, January 31, 2011 3:56 AMModerator
Hi MannyZanny,
I have tested the code you provided, I have not found any exceptions, could you help me reproduce your issue, and then I will do my best to resolve your issue.
I have upload the source code I tested on my side(no exception), the link is:
http://cid-41e44c402aaada87.office.live.com/self.aspx/For%20MannyZanny/ExceptionTest.rar
Best regards,
Sheldon _Xiao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.

- Marked As Answer by MannyZanny Wednesday, February 02, 2011 7:47 PM
-
Wednesday, February 02, 2011 7:47 PM
I tried it on 3 different computers and it works but I have no idea why it won't work on my development PC. I installed Windows Vista Business x64 about 2 months ago and installed Visual Studio 2008 but it seems the .NET framework is somehow malfunctioning. I don't want to reinstall and try to fix the problem since I already have my own calendar that works so I am going to use my custom control instead. I guess it's one of those "It doesn't work on my computer" problems. Thanks for the help anyways.
Manny.
-
Saturday, March 05, 2011 11:13 PM
I fixed this same issue in my code a few days ago.
Change the DataTemplate from "DayTitleTemplate" to "{x:Static CalendarItem.DayTitleTemplateResourceKey}"
This fixed the issue for me.
I was only able to reproduce it with a machine using UI Automation such as an HP TouchSmart.
Good luck.
Timothy McGrath
- Proposed As Answer by Friggers Thursday, October 27, 2011 5:28 PM

