Search code examples
wpfcaliburn.micromediaelement

Bind mediaelement to viewmodel


I´m working on a big project in wpf that uses Caliburn Micro. I have done a view that should view a movie. I´m trying to bind MediaElement Source to my file that I have in my ViewModel.

My View looks like this:

<TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Items}">
                <ContentControl cb:View.Model="{Binding}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </controls:ExtendedTreeView>
    <MediaElement Source="media" Visibility="{Binding IsIndexVisible, Converter={StaticResource InvertBoolToHiddenConverter}}" />

And in my viewmodel:

  public override void NavigateEnter()
    {
        //base.NavigateEnter();

        if (CanExpand)
        {
            base.Expand();
            return;
        }

        if (SelectedItem == null) return;

            var media = new MediaElement();

            media.LoadedBehavior = MediaState.Manual;
            media.Source = new Uri(@"C:/Users/v80770/Desktop/Movies/ATTV_bog.mpg");
            media.Play();
     }

            private Uri _mediaUri;
        public Uri MediaUri
        {
            get
            {
                return _mediaUri;
            }
            set
            {
                _mediaUri = value;
                NotifyOfPropertyChange(() => MediaUri);
            }
        }

  public override void NavigateEnter()
        {
            //base.NavigateEnter();

            if (CanExpand)
            {
                base.Expand();
                return;
            }

            if (SelectedItem == null) return;

            var test = (@"C:/Users/v80770/Desktop/Movies/ATTV_bog.mpg");
            var mediauri = new Uri(test);
            _mediaUri = mediauri;

            IsIndexVisible = false;
        }

But when I start my project nothing shows at all.


Solution

  • You need to bind the Uri as Source for Media Element. The Source Dependency Property expects type of Uri. You can verify it here.

    <MediaElement Source="{Binding MediaUri}" />
    

    Where MediaUri is defined as

    public Uri MediaUri {get;set; }