-2

I'm writing a WPF application and I have a MediaElement-Property called VideoPlayer in a class called ViewmodelVideos.

When I say

ViewModelVideos.VideosPlayer.Source = new Uri(text);

I get an exception:

Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll

I can't figure out why thats not working. Any ideas?

Edit:

"text" is a valid url which I can put into my browser and it works. No https, simple http://...

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
murkr
  • 634
  • 5
  • 27
  • 1
    Having a MediaElement in a view model sounds odd. A view model should not have any view elements. Besides that, my guess is that you're doing the call outside the UI thread. What is the exception message? – Clemens Sep 26 '17 at 22:00
  • @Clemens Can you tell me how to get the exception message? The programm doesn't stop, only the exception message `Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll` appears in the output window. There is no try catch around it either. – murkr Sep 27 '17 at 09:09
  • @Clemens the remark about doing the call outside the ui thread seems spot on. Do you know how to set the source from outside the ui thread? – murkr Sep 27 '17 at 09:12
  • 1
    `ViewModelVideos.VideosPlayer.Dispatcher.Invoke(() => ViewModelVideos.VideosPlayer.Source = new Uri(text));` – Clemens Sep 27 '17 at 09:21
  • @Clemens you sir, jsut made my day. please wrtie it as an answer. – murkr Sep 27 '17 at 09:29
  • Don't forget to move the MediaElement out of your view model. – Clemens Sep 27 '17 at 09:32
  • 1
    And where? code behind? – murkr Sep 27 '17 at 09:37
  • You may probably simply bind a MediaElement's Source property to a view model property of type Uri. – Clemens Sep 27 '17 at 09:44
  • But then I can't start and stop playback by buttons, can I? It's a videoplayer with GUI-buttons to control playback. (Also, do you want to write your answer as an answer, so I can accept it?) – murkr Sep 27 '17 at 09:49
  • Then your view may perhaps subscribe to a dedicated event in your view model. For an answer, I would prefer to close the question as duplicate, because this has been asked too often. However I can't, because I already voted to close as off-topic. You might simply delete it yourself. – Clemens Sep 27 '17 at 09:53

1 Answers1

0

@Clemens comment did the trick:

The problem was, that I was doing the call outside the UI thread.

Solution was

ViewModelVideos.VideosPlayer.Dispatcher.Invoke(() => ViewModelVideos.VideosPlayer.Source = new Uri(text)); 
murkr
  • 634
  • 5
  • 27