3

このチュートリアルに従いましたが、学んだことを自分のプロジェクトに適用できませんでした。

LineGraphオブジェクト(Dynamic Data Display)があり、LineGraph の太さが 0 のときに発生するイベントを作成したいと考えています。

このチュートリアルに従って、どのように記述すればよいですか?

4

2 に答える 2

13

Here is how I would do it with a RoutedEvent:

  1. Create a class that derives from LineGraph, let's say CustomLineGraph:

    public class CustomLineGraph : LineGraph {
    }
    
  2. Create our routed event like this:

    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. Now we override the StrokeThickness property so we can raise our custom routed event when the value of that property is 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. We are done !

于 2013-09-05T14:23:20.890 に答える
5

個人的には、通常はイベントを作成することを避け、代わりに を作成することを好みますdelegate。特にイベントが必要な特定の理由がある場合は、この回答を無視してください。私が sを使用することを好む理由は、追加のクラスdelegateを作成する必要がないことと、独自のパラメーター タイプを設定できることです。EventArgs

まず、デリゲートを作成しましょう。

public delegate void TypeOfDelegate(YourDataType dataInstance);

今ゲッターとセッター:

public TypeOfDelegate DelegateProperty { get; set; }

の in および out パラメータに一致するメソッドを作成しましょうdelegate

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

これで、このメソッドを this の (多数の) ハンドラーの 1 つとして設定できますdelegate

DelegateProperty += CanBeCalledAnything;

最後に、私たちの ... を呼び出しましょうdelegate。これは、イベントを発生させることと同じです。

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

の重要なチェックに注意してくださいnull。それでおしまい!パラメーターを増やしたり減らしたりしたい場合は、delegate宣言と処理方法からそれらを追加または削除するだけです...簡単です。

于 2013-09-05T14:01:57.883 に答える