【问题标题】:Add a custom property to a UserControl将自定义属性添加到 UserControl
【发布时间】:2012-12-14 13:43:22
【问题描述】:

我需要有关将自定义属性添加到 UserControl 的帮助。我创建了一个视频播放器用户控件,我想在另一个应用程序中实现它。我的 UserControl 中有一个 mediaElement 控件,我想从我的 UserControl 所在的应用程序访问 mediaElement.Source。

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

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

【问题讨论】:

  • 你能再添加一些代码吗?喜欢这个属性所在的类声明?
  • 如果将属性更改为字符串,那么它会显示出来吗?
  • 我编辑了问题。立即检查代码

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您需要从属性中更改您的 getset。尝试替换这个:

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

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      相关资源
      最近更新 更多