2014-07-08 48 views
4

我似乎在Xaml中暴露事件時遇到問題。我已經在像這樣的自定義用戶控件中聲明瞭一個公共事件處理程序。在自定義用戶控件中暴露事件 - Window Store應用程序

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中爲它指定一個事件時,找不到暴露的eventhandler。 I。

<local:FoodItemControl thumbnailClicked="SOMETHING" /> 

我是否在我找到的例子中缺少一些東西?

編輯:看起來我的問題是我將事件定義爲EventHandler < StringEventArgs>。它工作了一次,我改變這只是EventHandler我.e

public event EventHandler thumbnailedClicked; 

但我仍然不明白爲什麼?

回答

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