I’m working on custom control that I can use for interactions within my app UI. So, my idea is that control will bind to IInteractionsProvider which has it’s events. And then, I will call method on this provider that will raise event to my control to do what it needs to do.
Problem is, I have no idea how to properly subscribe to event InteractionRequired inside my custom control.
Basically, I don’t know how to properly hook and unhook event and at what time inside control.
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");
}
}
}
}
To attach to events on a dependency property (or to do anything with a dependency property when its assigned) you can use the callback delegate on the
PropertyMetadata.