Как подписаться на событие свойства Attached внутри пользовательского элемента управления в Silverlight? - PullRequest
2 голосов
/ 12 ноября 2011

Я работаю над пользовательским элементом управления, который я могу использовать для взаимодействия в пользовательском интерфейсе моего приложения.Итак, моя идея заключается в том, что элемент управления будет привязан к IInteractionsProvider, в котором есть события.И затем я вызову метод этого провайдера, который вызовет событие для моего контроля, чтобы сделать то, что ему нужно.

Проблема в том, что я не знаю, как правильно подписаться на событие InteractionRequired в моем пользовательском элементе управления.

В принципе, я не знаю, как правильно подключить и отсоединить событие и при чемвремя внутри контроля.

public interface IInteractionsProvider
    {
        event EventHandler InteractionRequested;

        void RequestInteraction(Action<object> callback);
    } 



public class MyInteractions : Control
    {
        public static readonly DependencyProperty ContainerProperty =
            DependencyProperty.Register("Container", typeof(Grid), typeof(IdattInteractions), new PropertyMetadata(null));

        public static readonly DependencyProperty InteractionsProviderProperty =
            DependencyProperty.Register("InteractionsProvider", typeof(IInteractionsProvider), typeof(IdattInteractions), new PropertyMetadata(null));

        public IdattInteractions()
        {
            DefaultStyleKey = typeof(MyInteractions);
        }

        public Grid Container
        {
            get { return GetValue(ContainerProperty) as Grid; }
            set { this.SetValue(ContainerProperty, value); }
        }

        public IInteractionsProvider InteractionsProvider
        {
            get { return (IInteractionsProvider)GetValue(InteractionsProviderProperty); }
            set { this.SetValue(InteractionsProviderProperty, value); }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (System.ComponentModel.DesignerProperties.IsInDesignTool) return;

            if (this.InteractionsProvider == null)
            {
                throw new NotSupportedException("InteractionsProvider wasn't specified. If you don't need interactions on this view - please remove MyInteractions from XAML");
            }

            if (this.Container != null)
            {
                if (this.Container.GetType() != typeof(Grid))
                {
                    throw new NotSupportedException("Specified container must be of Grid type");
                }
            }
            else
            {
                this.Container = TreeHelper.FindParentGridByName(this, "LayoutRoot") ?? TreeHelper.FindParent<Grid>(this);

                if (this.Container == null)
                {
                    throw new NotSupportedException("Container wasn't specified and parent Grid wasn't found");
                }
            }
        }
    }

Ответы [ 2 ]

1 голос
/ 12 ноября 2011

Чтобы присоединить события к свойству зависимости (или сделать что-нибудь со свойством зависимости, когда оно назначено), вы можете использовать делегат обратного вызова на PropertyMetadata.

    public static readonly DependencyProperty InteractionsProviderProperty = 
        DependencyProperty.Register("InteractionsProvider", typeof(IInteractionsProvider), typeof(IdattInteractions), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged)); 

    private static void OnInteractionsProviderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

         var source = d As MyInteractions;
         if (source ! = null)
         {
             var oldValue = (IInteractionsProvider)e.OldValue;
             var newValue = (IInteractionsProvider)e.NewValue;
             source.OnInteractionsProviderPropertyChanged(oldValue, newValue);
         }
    }
    private void OnInteractionsProviderPropertyChanged(IInteractionsProvider oldValue, IInteractionsProvider newValue)
    {
         if (oldValue != null)
              oldValue -= InteractionsProvider_InteractionRequested;

         if (newValue != null)
              newValue += InteractionsProvider_InteractionRequested;
    }
    private void InteractionsProvider_InteractionRequested(object sender, EventArgs e)
    {
        // Do Stuff
    }
0 голосов
/ 12 ноября 2011

Это то, что вы ищете?

public IInteractionsProvider InteractionsProvider 
{ 
    get { return (IInteractionsProvider)GetValue(InteractionsProviderProperty); } 
    set {
        var oldValue = this.InteractionsProvider;
        if (oldValue != null)
            oldValue.InteractionRequested -= this.HandleInteractionRequested;
        if (value != null)
            value.InteractionRequested += this.HandleInteractionRequested;
        this.SetValue(InteractionsProviderProperty, value);
    } 
} 

private void HandleInteractionRequested(object sender, EventArgs e)
{
    //...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...