2014-01-28 71 views
1

我已經搜索了很長時間,找不到這個問題的答案。這可能只是一個不知道要搜索什麼的問題。是否有可能爲FrameworkElements提供「全局」處理程序?「全球」事件處理程序

例如:

在頁1

<Grid x:Name="Grid1" Unloaded="GlobalHandler"/> 

在頁2

<Grid x:Name="Grid2" Unloaded="GlobalHandler"/> 

全球處理程序?我在哪裏可以存儲這些代碼,以便它們可用於兩個網格?

private void GlobalHandler(object sender, RoutedEventArgs e) 
{ 
    //Do something with grid here 
} 

回答

2

創建一個具有相同簽名的靜態方法,然後在您的頁面中,從您的個人處理程序調用靜態方法。

public class EventHandlerHelper 
{ 
    public static GlobalUnload(object sender, RoutedEventArgs e) 
    { 
    // work 
    } 
} 

public class Page1 
{ 
    public void GlobalHandler(object sender, RoutedEventArgs e) 
    { 
     EventHandlerHelper.GlobalUnload(sender, e); 
    } 
} 

public class Page2 
{ 
    public void GlobalHandler(object sender, RoutedEventArgs e) 
    { 
     EventHandlerHelper.GlobalUnload(sender, e); 
    } 
} 
+1

柵格在不同的頁面雖然 – Jay

+1

我不好,向上過時的帖子來反映, –

+0

優秀。謝謝。我在想這樣的事情,但是如果有一種方法可以做到這一點,而不必每次都調用靜態方法,我們仍然很好奇。好吧! :) – philorube

1

如果你想堅持多一點XAML你可以在一個ResourceDictionary聲明EventSetter風格和合並所述字典成永遠的頁面也需要它。

直從該MSDN forum thread由於用戶Kevin Pan

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        x:Class="MyResource.MyResourceDictionary" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Style TargetType="Grid" x:Key="mycanvasstyle"> 
    <EventSetter Event="Unloaded"Handler="MyResourceDictionary_GlobalHandler"/> 
    </Style> 
</ResourceDictionary> 

在部分類爲ResourceDictionary

void MyResourceDictionary_GlobalHandler(object sender, MouseButtonEventArgs e) 
{ 
    //Do something with grid here 
} 

,然後將此添加到每個頁數XAML

<Page> 
    <Page.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 
    </Page.Resources> 

    <!-- rest of page --> 

</Page> 
+0

我upvoted這個。但是這個答案對這個問題是無效的。 Silverlight中沒有'EventSetter'。 – McGarnagle