簡體   English   中英

將自定義屬性添加到UserControl

[英]Add a custom property to a UserControl

我需要將自定義屬性添加到UserControl的幫助。 我創建了一個Video Player 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();
        }

我似乎在屬性框中找不到屬性。 有什么幫助嗎?

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

您需要從屬性更改獲取設置 嘗試替換此:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM