2014-02-28 12 views
1

我在我的應用程序中有一些窗口是打算封裝在其樣式中的<ContentPresenter>。在這種風格中,我構建了一個模板,其中包含一些自定義的用戶控件,如自定義標題欄和某處,其中包含任何窗口的內容ContentPresenter。目標是提取每個窗口所需的xaml,並在樣式中放入一個模板。 這正是wpf的用途。在其他地方的捕獲事件在後面的代碼中

然後,我希望在用戶點擊任何地方的內容時,從所有這些窗口中引發的事件。所以,我在樣式補充說:

<ContentPresenter PreviewMouseDown="somethingMouseDowned" /> 

需要注意的是,首先,我申請這窗口(S)和內部grisd,在後面(xaml.cs)的代碼,我處理的事件,做什麼我想,一切都很好。

但我希望事件處理在窗口中是不可見的。這就是爲什麼我將PreviewMouseDown放入樣式中的原因。我也不希望我的代碼中有任何處理代碼。

問題是我不知道如何處理事件,而不是在後面的代碼中。我需要替代品。

在此先感謝

+0

什麼樣的控制?這是一個用戶控件(WPF)? – Paparazzi

+1

對於XAML在一般情況下如何工作,您似乎有幾個嚴重的誤解。我建議你先從基礎開始,然後在嘗試創建複雜的複合自定義樣式的UI之前,在WPF XAML中遵循一些「Hello,World!」類型的教程。 –

+0

我重新寫了我的問題。請重新考慮@HighCore謝謝。 –

回答

1

您還可以使用AttachedProperty(EventToCommand)和綁定此事件的命令(ICommand的)在viewmodel中。 下面是代碼:

public static class ContenPreviewMouseDownCommandBinding 
    { 
     public static readonly DependencyProperty CommandProperty = 
      DependencyProperty.RegisterAttached("Command", typeof (ICommand), typeof (ContenPreviewMouseDownCommandBinding), 
      new PropertyMetadata(default(ICommand), HandleCommandChanged)); 

     private static void HandleCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
      var contentPresenter = d as ContentPresenter; 
      if(contentPresenter!=null) 
      { 
       contentPresenter.PreviewMouseDown += new MouseButtonEventHandler(contentPresenter_PreviewMouseDown); 
      } 
     } 

     static void contentPresenter_PreviewMouseDown(object sender, MouseButtonEventArgs e) 
     { 
      var contentPresenter = sender as ContentPresenter; 
      if(contentPresenter!=null) 
      { 
       var command = GetCommand(contentPresenter); 
       command.Execute(e); 
      }    
     } 

     public static void SetCommand(ContentPresenter element, ICommand value) 
     { 
      element.SetValue(CommandProperty, value); 
     } 

     public static ICommand GetCommand(ContentPresenter element) 
     { 
      return (ICommand) element.GetValue(CommandProperty); 
     } 
    } 
在XAML

<ContentPresenter CommandBindings:ContenPreviewMouseDownCommandBinding.Command="{Binding Path=AnyCommandInScopeOfDataContext}"> 

       </ContentPresenter> 
+0

非常感謝您的回覆!非常感激。 :) –

0

在一定程度上,你將不得不在你的代碼隱藏一些代碼做一些事情來處理該事件。但是,爲了最大限度地減少代碼隱藏中的代碼量,您可以利用MVP pattern並將所有事件處理封裝到演示者類中,或者可以使用其他工具集,例如Galasoft MVVMLight Messenger,如SO discussion中所述。

0

如果您有其他類的靜態事件處理程序嘗試使用
{X:靜態anotherClass.somethingMouseDowned}

相關問題