将自定义属性添加到UserControl

时间:2012-12-14 13:43:22

标签: c# silverlight user-controls expression-blend-4 custom-properties

我需要帮助向UserControl添加自定义属性。我创建了一个Video Player UserControl,我想在另一个应用程序中实现它。我的UserControl中有一个mediaElement控件,我想从应用程序访问mediaElement.Source,我的UserControl将在哪里。

我试过了:[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();
        }

我似乎无法在属性框中找到属性。对此有何帮助?

2 个答案:

答案 0 :(得分:0)

您对DependencyProperty CLR包装器使用了不正确的语法(getter / setter) 使用以下正确的代码:

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;
}

答案 1 :(得分:0)

您需要从属性中更改获取设置。尝试替换它:

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

有了这个:

public System.Uri VideoPlayerSource
{
    get { return (System.Uri)GetValue(VideoPlayerSourceProperty); }
    set { SetValue(VideoPlayerSourceProperty, value); }
}