1

我需要帮助将自定义属性添加到UserControl。我创建了一个视频播放器用户控件,我想在另一个应用程序中实现它。我的UserControl中有一个mediaElement控件,我想从我的UserControl的应用程序访问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(); 
     } 

无法找到在属性框中属性。有关于此的任何帮助?

+0

你可以添加一些更多的代码?就像这个属性所在的类声明一样? – juanreyesv

+0

如果将属性更改为字符串,那么它会显示出来吗? –

+0

我编辑的问题。现在检查代码 – JohnTurner

回答

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

谢谢,它的工作:) – JohnTurner

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); } 
} 
相关问题