0

Im trying to create an overlay system for media items. To do so I add a canvas to my form. Via code I add a media element to the canvas.

mediaPlayer = new MediaElement();
canvas.Children.Add(mediaPlayer);
mediaPlayer.HorizontalAlignment = HorizontalAlignment.Left;
mediaPlayer.VerticalAlignment = VerticalAlignment.Top;
mediaPlayer.Height = 1080;
mediaPlayer.Width = 1920;
mediaPlayer.Source = new Uri(ConfigurationManager.AppSettings["VideoFile"], UriKind.Relative);

mediaPlayer.LoadedBehavior = MediaState.Manual;

mediaPlayer.Play();
mediaPlayer.MouseDown +=mediaPlayer_MouseDown;

When I launch the app I get a Exception on the canvas.Children.Add(mediaPlayer): Object reference not set to an instance of an object. It does not mather if I place this line after the instantiate, right before the Play() call or just after the play() call.

I did some tests, when adding it in the designer it works, though you are not alow to start maunally, when setting then LoadedBehavior to manual it crashes also (same error). When adding the media element to the form it does work as expected, though now I cannot overlay elements... What am I doing wrong?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Patrick
  • 2,730
  • 4
  • 33
  • 55
  • 1
    First of all it would be nice if you state the line where the exception occurs. I would suggest you to use the [Debugger](http://msdn.microsoft.com/en-us/library/vstudio/sc65sadd.aspx) to find out more about your problem. –  Oct 07 '13 at 11:35
  • 1
    I would agree with @wonko79... *you* are the only person that can debug your code. Hover your mouse pointer over the various objects in your code when the `Exception` occurs to find out which one is `null` and if necessary, come back here with that information for help. – Sheridan Oct 07 '13 at 12:44
  • Ok.. after retesting the thing, I found out that when I drag/drop an element to a WPF element, that element stys null... Weird, I have to look why this is. – Patrick Oct 07 '13 at 16:30
  • Forgot my InitializeComponent method :( – Patrick Oct 07 '13 at 16:40
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 13 '13 at 02:46
  • Yeah, I know a null ref exception. In my "I do not know WPF" world I did everything alright. By accident I removed the InitializeComponent method. That was causing my form elements to stay uninitialized... Just a moment of learning WPF... – Patrick Oct 13 '13 at 08:53

1 Answers1

0

The problem was not with the code above. The problem is that in WPF you NEED to call InitializeComponent. This method is standard generated when creating a new Form. By accident I removed that line of code. This causes all form elements not to be initialized.

Patrick
  • 2,730
  • 4
  • 33
  • 55