在Custom Usercontrol - Window Store App中公开事件

时间:2014-07-08 22:12:50

标签: c# xaml user-controls windows-store-apps

我似乎遇到了在Xaml中暴露事件的问题。我在自定义用户控件中声明了一个公共事件处理程序。

public sealed partial class FoodItemControl : UserControl
{
    public event EventHandler<StringEventArgs> thumbnailClicked;

    public FoodItemControl()
    {
        InitializeComponent();
        (this.Content as FrameworkElement).DataContext = this;
    }



    private void Thumbnail_Tapped(object sender, TappedRoutedEventArgs e)
    {
        var handler = thumbnailClicked;
        if (handler != null)
        {
            handler(this, new StringEventArgs());
        }
    }
}

但是当我在xaml中为它分配事件时,无法找到暴露的事件处理程序。即

<local:FoodItemControl thumbnailClicked="SOMETHING" />

我在发现的例子中遗漏了什么?

编辑:我的问题似乎是我将事件定义为EventHandler&lt; StringEventArgs&gt;。一旦我将其改为EventHandler I.e

,它就可以工作了
public event EventHandler thumbnailedClicked;

但是我还是不明白为什么?

2 个答案:

答案 0 :(得分:1)

您必须创建依赖项属性并注册该属性以在用户控件中公开它:

public sealed partial class FoodItemControl : UserControl
{
    public EventHandler thumbnailClicked
    {
        get { return (EventHandler)GetValue(thumbnailClickedProperty); }
        set { SetValue(thumbnailClickedProperty, value); }
    }

    public static readonly DependencyProperty thumbnailClickedProperty =
  DependencyProperty.Register("thumbnailClicked", typeof(EventHandler),
    typeof(FoodItemControl), new PropertyMetadata(""));


    public FoodItemControl()
    {
        this.InitializeComponent();
        (this.Content as FrameworkElement).DataContext = this;
    }
}

答案 1 :(得分:0)

您还可以使用TypedEventHandler类型:

public event TypedEventHandler<FoodItemControl, StringEventArgs> thumbnailClicked;

这可让您指定从EventArgs派生的事件参数类。