Instead of posting my code here, I will just outline the basic tree in my program. I have a TabControl with an Item in it and a few "treed" elements as follows:
TabControl
->TabItem
->UserControl(Grid with Columns and Rows)
->ScrollViewer(Within one of the Grid.Columns/Grid.Rows, also part of the UserControl)
->Grid myGrid(added in code during runtime)
->...a couple more things
Now in code I add an event to myGrid
and I noticed the error when I tried to manually scroll the ScrollViewer
, only when ctrl is pressed.
myGrid.PreviewMouseWheel += HandlePreviewMouseWheel;
private void HandlePreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
bool isCtrl = Keyboard.IsKeyDown(Key.LeftCtrl);
if (isCtrl)
{
if (e.Delta > 0)
((sender as Grid).Parent as ScrollViewer).LineUp();
else
((sender as Grid).Parent as ScrollViewer).LineDown();
}
}
That threw an exception on the type casting: An exception of type 'System.NullReferenceException' occurred in dfviewer.exe but was not handled in user code. Additional information: Object reference not set to an instance of an object.
I noticed that sender
is actually not myGrid
but instead labled as {System.Windows.Controls.TabControl Items.Count:1}
. But how is that possible if I explicitly added the event to myGrid
? Is it possible that I am missing something else here?
I have tried using MouseWheel
instead of PreviewMouseWheel
and it gave me the same issue and both e.Source
and e.OriginalSource
are not myGrid
but instead "my UserControl"
and "some Child of myGrid"
, respecitvely.
The only other post that I found a bit similar to this is here but that is unfortunately not exactly my issue here.
Hopefully, somebody can help me, because I am really lost...