/ / UserControlからMouseButtonEventを発生させると、メインウィンドウはMouseButtonEventArgsにアクセスできない - wpf、イベント、ユーザーコントロール、イベントバブリング

UserControlからMouseButtonEventを呼び出すと、MainWindowはMouseButtonEventArgsにアクセスできません - wpf、events、user-controls、event-bubbling

まだ急なWPF山を登って、そして苦しんでいます。

私はUserControlを定義しました、そして私のMainWindowはUserControlの中のコントロールから来るMouseButtonEventArgsを取得する必要があります(例えばマウスe.GetPositionのように)

後ろのUserControlコードで、私は登録をしました、そして、私はバブリングイベントを上げます。

public static readonly RoutedEvent MyButtonDownEvent = EventManager.RegisterRoutedEvent("MyMouseButtonDown", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));
public event RoutedEventHandler MyButtonDown {
add { AddHandler(MyButtonDownEvent, value); }
remove { RemoveHandler(MyButtonDownEvent, value); }
}
private void MyMouseButtonDownHandler(object sender, MouseButtonEventArgs e) {
RaiseEvent(new RoutedEventArgs(MyButtonDownEvent ));
}

今私のメインウィンドウで私はこのようにUserControlを宣言します:

<local:MyUserControl MouseDown="MyUserControl_MouseDown"/>

そしてこの背後にあるコード

private void MyUserControl_MouseDown(object sender, RoutedEventArgs e)

そして私はUserControlからイベントを受け取ります、しかしArgsはRoutedEventArgsです(これは普通です)が、私はMouse e.GetPositionを取得するために必要なMouseButtonEventArgsへのアクセスを持っていません。

この場合、どのようなエレガントな解決策を提案しますか?

回答:

回答№1は1

なぜあなたはあなた自身を定義しますか MouseDown イベント中 UserControl すでに通常のMouseDownイベントがありますか?

とにかく、あなたがを使用するイベントを定義すれば RoutedEventHandler それはあなたが "で立ち往生することになるだろう"ことはほとんど驚くべきことでは RoutedEventHandler。あなたはそれをこのように宣言しました:

public static readonly RoutedEvent MyButtonDownEvent = EventManager.RegisterRoutedEvent("MyMouseButtonDown", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

それが言うところのビットに注意してください typeof(RoutedEventHandler)

私が間違っていなければ、あなたのコードは代わりにこのようになるはずです。

    public static readonly RoutedEvent MyButtonDownEvent =
EventManager.RegisterRoutedEvent
("MyButtonDown",
RoutingStrategy.Bubble,
typeof(MouseButtonEventHandler),
typeof(MyUserControl));

public event MouseButtonEventHandler MyButtonDown
{
add { AddHandler(MyButtonDownEvent, value); }
remove { RemoveHandler(MyButtonDownEvent, value); }
}

既存のMouseDownイベントをカスタムイベントに伝播する方法の例:

InitializeComponent();
this.MouseDown += (s, e) => {
RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, e.ChangedButton)
{
RoutedEvent = MyButtonDownEvent
});
};

回答№2の場合は0

私はついにそれを手に入れたと思います(少なくとも私は願っています):

背後にあるコードを書くと:

        public event EventHandler<MouseButtonEventArgs> MyRightButtonDownHandler;
public void MyRightButtonDown(object sender, MouseButtonEventArgs e) {
MyRightButtonDownHandler(sender, e);
}

次に、コンシューマ(メインウィンドウ)のXAMLで、

<local:GlobalDb x:Name="globalDb"  MyRightButtonDownHandler="globalDb_MyRightButtonDownHandler"/>

そして背後にある消費者コードでは:

    private void globalDb_MyRightButtonDownHandler(object sender, MouseButtonEventArgs e) {
Console.WriteLine("x= " + e.GetPosition(null).X + " y= " + e.GetPosition(null).Y);
}

より良い解決策があるかどうかを教えてください(設計方針により - 私が勤務する場所で確立された規則 - 私のアプリケーションのすべてのイベント処理はXAMLに現れなければなりません)。

ご協力ありがとうございます