【发布时间】:2011-12-27 08:46:00
【问题描述】:
我正在开发可用于在我的应用 UI 中进行交互的自定义控件。所以,我的想法是控件将绑定到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");
}
}
}
}
【问题讨论】:
标签: c# silverlight xaml mvvm