2016-01-14 22 views
0

我創建一個自定義Shape類:創建形狀類內部的鼠標事件

public class CustomBox : Shape 
{ 
    protected override Geometry DefiningGeometry 
    { 
     get 
     { 
      Stroke = Brushes.Red; 
      var pathGeometry = new PathGeometry(); 

      pathGeometry.AddGeometry(new RectangleGeometry(new Rect(new Point(100, 200), new Point(400, 400))); 

      var formattedText = new FormattedText("CustomBox", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Times New-Roman"), 14, Brushes.Red); 
      var textGeometry = formattedText.BuildGeometry(new Point(100, 200)); 

      pathGeometry.AddGeometry(textGeometry); 
      return pathGeometry; 
     } 
    } 
} 

我想補充/覆蓋/實施內部Mouse事件如MouseDownMouseUpMouseMove等將定義CustomBox對象的行爲。

例如:

我想補充時,我將鼠標懸停在對象時發生的「行爲」 - 其結果將是,該Rectangle將被突出顯示(通過增加StrokeThickness例如)。

可以添加這樣的功能,而不必將對象註冊到Mouse事件外部(創建CustomBox並將其添加到Canvas的類)?

+1

看起來像XY問題。您的示例可以作爲樣式觸發器來實現。如果您想對其他鼠標事件作出反應,只需重寫適當的'OnPreviewMouse ***'/'OnMouse ***'方法,例如'OnMouseMove'。 – Dennis

回答

0

請嘗試下: 1. XAML代碼:

<Window x:Class="CustomShapeSoHelpAttempt.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:customShapeSoHelpAttempt="clr-namespace:CustomShapeSoHelpAttempt" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <customShapeSoHelpAttempt:CustomBox HorizontalAlignment="Center" VerticalAlignment="Center" Stroke="Red" StrokeThickness="1" Fill="#00FFFFFF"/> 
</Grid></Window> 

2. CustomBox代碼:

public class CustomBox : Shape 
{ 
    private Brush _originalBrush; 
    private double _originalThickness; 

    protected override Geometry DefiningGeometry 
    { 
     get 
     { 

      var pathGeometry = new PathGeometry(); 

      pathGeometry.AddGeometry(new RectangleGeometry(new Rect(new Point(0, 0), new Point(200, 200)))); 

      var formattedText = new FormattedText("CustomBox", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, 
       new Typeface("Times New-Roman"), 14, Brushes.Black); 
      var textGeometry = formattedText.BuildGeometry(new Point(0, 0)); 

      pathGeometry.AddGeometry(textGeometry); 
      return pathGeometry; 
     } 
    } 

    protected override void OnMouseEnter(MouseEventArgs e) 
    { 
     base.OnMouseEnter(e); 
     _originalThickness = StrokeThickness; 
     StrokeThickness = 2; 
     _originalBrush = Fill; 
     Fill = Brushes.Aqua; 
    } 

    protected override void OnMouseLeave(MouseEventArgs e) 
    { 
     base.OnMouseLeave(e); 
     StrokeThickness = _originalThickness; 
     Fill = _originalBrush; 
    } 


} 

正如你所看到的,你可以覆蓋所有的控制有關鼠標的事件處理程序和在那裏執行你的邏輯。所有這些都是由於你的控件派生自Shape控件並具有其所有事件處理程序。 如果您遇到代碼問題,我很樂意提供幫助。 此致敬禮。