2013-09-05 64 views
2

我跟着this tutorial,但我不能將我學到的東西應用到我的項目中。如何創建自定義路由事件? WPF c#

我有一個LineGraph對象(Dynamic Data Display),我想創建一個引發的事件時LineGraph的厚度等於0

我怎麼把它寫下面這個教程?

+0

你有什麼確切的問題,爲什麼你不能應用教程? –

+1

我不工作D3,但它似乎'LineGraph'對象沒有厚度屬性? –

+0

你可以發佈一些代碼,以便我們可以看到問題是什麼? –

回答

3

就個人而言,我通常避免創建事件,寧願創建delegate s。如果您有某些特殊原因需要特別事件,請忽略此答案。我更喜歡使用delegate的原因是您不需要創建其他EventArgs類,我也可以設置自己的參數類型。

首先,讓我們創建一個委託:

public delegate void TypeOfDelegate(YourDataType dataInstance); 

現在getter和setter:

public TypeOfDelegate DelegateProperty { get; set; } 

現在,讓我們創建一個將在匹配方法和出delegate的參數:

public void CanBeCalledAnything(YourDataType dataInstance) 
{ 
    // do something with the dataInstance parameter 
} 

現在我們可以將此方法設置爲此中的一個(多個)處理程序:

DelegateProperty += CanBeCalledAnything; 

最後,讓我們把我們的delegate ...這相當於引發事件:

if (DelegateProperty != null) DelegateProperty(dataInstanceOfTypeYourDataType); 

注意事項null重要的檢查。就是這樣了!如果您想要更多或更少的參數,只需將它們從delegate聲明和處理方法中添加或刪除即可...很簡單。

12

這裏是我如何與一個RoutedEvent做到這一點:

  1. 創建從LineGraph派生的類,比方說CustomLineGraph

    public class CustomLineGraph : LineGraph { 
    } 
    
  2. 這樣創建我們的路由事件:

    public class CustomLineGraph : LineGraph { 
    
        public static readonly RoutedEvent ThicknessEvent = EventManager.RegisterRoutedEvent("Thickness", RoutingStrategy.Bubble, typeof(RoutedEventHandler, typeof(CustomLineGraph)); 
    
        // .NET event wrapper 
        public event RoutedEventHandler Thickness 
        { 
         add { AddHandler(CustomLineGraph.ThicknessEvent, value); } 
         remove { RemoveHandler(CustomLineGraph.ThicknessEvent, value); } 
        } 
    } 
    
  3. 現在我們覆蓋th e StrokeThickness property,因此當該屬性的值爲0時,我們可以提高我們的自定義路由事件。

    public class CustomLineGraph : LineGraph { 
    
        public static readonly RoutedEvent ThicknessEvent = EventManager.RegisterRoutedEvent("Thickness", RoutingStrategy.Bubble, typeof(RoutedEventHandler, typeof(CustomLineGraph)); 
    
        // .NET event wrapper 
        public event RoutedEventHandler Thickness 
        { 
         add { AddHandler(CustomLineGraph.ThicknessEvent, value); } 
         remove { RemoveHandler(CustomLineGraph.ThicknessEvent, value); } 
        } 
    
        public override double StrokeThickness { 
         get { return base.StrokeThickness; } 
         set 
         { 
          base.StrokeThickness = value; 
          if (value == 0) 
           RaiseEvent(new RoutedEventArgs(CustomLineGraph.ThicknessEvent, this)); 
         } 
        } 
    } 
    
  4. 我們完成了!