简体   繁体   English

将自定义属性添加到UserControl

[英]Add a custom property to a UserControl

i need help with adding a custom property to a UserControl. 我需要将自定义属性添加到UserControl的帮助。 I created a Video Player UserControl and i want to implement it in another application. 我创建了一个Video Player UserControl,我想在另一个应用程序中实现它。 I have a mediaElement control in my UserControl and i want to access mediaElement.Source from the app where will my UserControl be. 我的UserControl中有一个mediaElement控件,我想从我的UserControl所在的应用中访问mediaElement.Source。

I tried this: [Player.xaml.cs] 我尝试了这个: [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? 有什么帮助吗?

You are using incorrect syntax for DependencyProperty CLR wrappers(getter/setter). 您对DependencyProperty CLR包装器(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;
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM