Question

i need help with adding a custom property to a UserControl. I created a Video Player UserControl and i want to implement it in another application. I have a mediaElement control in my UserControl and i want to access mediaElement.Source from the app where will my UserControl be.

I tried this: [Player.xaml.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

    namespace VideoPlayer
    {
    public partial class Player : UserControl
    {
        public static readonly DependencyProperty VideoPlayerSourceProperty =
        DependencyProperty.Register("VideoPlayerSource", typeof(System.Uri), typeof(Player), null);

        public System.Uri VideoPlayerSource
        {
            get { return mediaElement.Source; }
            set { mediaElement.Source = value; }
        }


        public Player()
        {
            InitializeComponent();
        }

I can't seem to find property in properties box. Any help about this?

Was it helpful?

Solution

You are using incorrect syntax for DependencyProperty CLR wrappers(getter/setter).
Use the following correct code:

public static readonly DependencyProperty VideoPlayerSourceProperty = DependencyProperty.Register("VideoPlayerSource", 
    typeof(System.Uri), typeof(Player),
    new PropertyMetadata(null, (dObj, e) => ((Player)dObj).OnVideoPlayerSourceChanged((System.Uri)e.NewValue)));

public System.Uri VideoPlayerSource {
    get { return (System.Uri)GetValue(VideoPlayerSourceProperty); } // !!!
    set { SetValue(VideoPlayerSourceProperty, value); } // !!!
}
void OnVideoPlayerSourceChanged(System.Uri source) {
    mediaElement.Source = source;
}

OTHER TIPS

You need to change your get and set from the property. Try replacing this:

public System.Uri VideoPlayerSource
{
    get { return mediaElement.Source; }
    set { mediaElement.Source = value; }
}

With this:

public System.Uri VideoPlayerSource
{
    get { return (System.Uri)GetValue(VideoPlayerSourceProperty); }
    set { SetValue(VideoPlayerSourceProperty, value); }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top