2013-08-07 66 views
2

我想在XAML Dictionary中的Border上使用RoutedEventRoutedEvent來自模板所屬的類,我如何實現這一目標?通過TemplateBinding添加RoutedEvent

ModernWindow.cs

/// <summary> 
/// Gets fired when the logo is clicked. 
/// </summary> 
public static readonly RoutedEvent LogoClickEvent = EventManager.RegisterRoutedEvent("LogoClickRoutedEventHandler", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ModernWindow)); 

/// <summary> 
/// The routedeventhandler for LogoClick 
/// </summary> 
public event RoutedEventHandler LogoClick 
{ 
    add { AddHandler(LogoClickEvent, value); } 
    remove { RemoveHandler(LogoClickEvent, value); } 
} 

/// <summary> 
/// 
/// </summary> 
protected virtual void OnLogoClick() 
{ 
    RaiseEvent(new RoutedEventArgs(LogoClickEvent, this)); 
} 

ModernWindow.xaml

<!-- logo --> 
<Border MouseLeftButtonDown="{TemplateBinding LogoClick}" Background="{DynamicResource Accent}" Width="36" Height="36" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,76,0"> 
    <Image Source="{TemplateBinding Logo}" Stretch="UniformToFill" /> 
</Border> 

回答

2

我終於找到一個解決方案,我用InputBindings然後Commands

<Border.InputBindings> 
    <MouseBinding Command="presentation:Commands.LogoClickCommand" Gesture="LeftClick" /> 
</Border.InputBindings> 

它不正是我想要的,但它的工作原理:)

1

我想在你的情況,你可以使用EventSetter,它只是設計來做到這一點。對你來說會是這個樣子:

<Style TargetType="{x:Type SomeControl}"> 
    <EventSetter Event="Border.MouseLeftButtonDown" Handler="LogoClick" /> 
    ... 

</Style> 

Note:EvenSetter無法通過觸發器設置並不能包含在主題資源字典中的風格中使用,因此它通常被放在開頭目前的風格。

欲瞭解更多信息,請參見:

EventSetter Class in MSDN

或者,如果您需要在ResourceDictionary使用它,你可以做不同的。創建DependencyProperty(也可以附加)。例如附有DependencyProperty

屬性定義:

public static readonly DependencyProperty SampleProperty = 
              DependencyProperty.RegisterAttached("Sample", 
              typeof(bool), 
              typeof(SampleClass), 
              new UIPropertyMetadata(false, OnSample)); 

private static void OnSample(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
{ 
    if (e.NewValue is bool && ((bool)e.NewValue) == true) 
    { 
     // do something... 
    } 
} 

如果您嘗試設置我們的財產的價值,被稱爲On Sample,在其中你就可以做你需要的東西(幾乎以及事件)。

設置屬性的值,取決於事件,你可能會喜歡:

<EventTrigger SourceName="MyBorder" RoutedEvent="Border.MouseLeftButtonDown"> 
    <BeginStoryboard> 
     <Storyboard> 
      <ObjectAnimationUsingKeyFrames Storyboard.TargetName="MyBorder" Storyboard.TargetProperty="(local:SampleClass.Sample)"> 
       <DiscreteObjectKeyFrame KeyTime="0:0:0"> 
        <DiscreteObjectKeyFrame.Value> 
         <sys:Boolean>True</sys:Boolean> 
        </DiscreteObjectKeyFrame.Value> 
       </DiscreteObjectKeyFrame> 
      </ObjectAnimationUsingKeyFrames> 
     </Storyboard> 
    </BeginStoryboard> 
</EventTrigger> 
+0

THX,但究竟這就是問題所在,我需要它的主題詞典一個自定義用戶控件... – Knerd

+0

@Knerd:請參閱有關依賴屬性的答案。 –