質問

WPF StackPanelのダブルクリックおよびシングルクリックイベントを処理できる必要があります。しかし、StackPanelのDoubleClickイベントのようなものはありません。 これら2つのEventHandlerで2つの異なる操作を行いたい。

それを行う方法はありますか?

ありがとう

役に立ちましたか?

解決

最善の方法は、独自のマウスボタンハンドラーをタイムアウトに設定することです。タイムアウト期間内にイベントが再度発生した場合は、ダブルクリックメッセージを発生させます。そうでない場合は、シングルクリックハンドラーを呼び出します。サンプルコードを次に示します(編集:もともとこちら):

/// <summary>
/// For double clicks
/// </summary>
public class MouseClickManager {
    private event MouseButtonEventHandler _click;
    private event MouseButtonEventHandler _doubleClick;

    public event MouseButtonEventHandler Click {
        add { _click += value; }
        remove { _click -= value; }
    }

    public event MouseButtonEventHandler DoubleClick {
        add { _doubleClick += value; }
        remove { _doubleClick -= value; }
    }

    /// <summary>
    /// Gets or sets a value indicating whether this <see cref="MouseClickManager"/> is clicked.
    /// </summary>
    /// <value><c>true</c> if clicked; otherwise, <c>false</c>.</value>
    private bool Clicked { get; set; }

    /// <summary>
    /// Gets or sets the timeout.
    /// </summary>
    /// <value>The timeout.</value>
    public int DoubleClickTimeout { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="MouseClickManager"/> class.
    /// </summary>
    /// <param name="control">The control.</param>
    public MouseClickManager(int doubleClickTimeout) {
        this.Clicked = false;
        this.DoubleClickTimeout = doubleClickTimeout;
    }

    /// <summary>
    /// Handles the click.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
    public void HandleClick(object sender, MouseButtonEventArgs e) {
        lock (this) {
            if (this.Clicked) {
                this.Clicked = false;
                OnDoubleClick(sender, e);
            }
            else {
                this.Clicked = true;
                ParameterizedThreadStart threadStart = new ParameterizedThreadStart(ResetThread);
                Thread thread = new Thread(threadStart);
                thread.Start(e);
            }
        }
    }

    /// <summary>
    /// Resets the thread.
    /// </summary>
    /// <param name="state">The state.</param>
    private void ResetThread(object state) {
        Thread.Sleep(this.DoubleClickTimeout);

        lock (this) {
            if (this.Clicked) {
                this.Clicked = false;
                OnClick(this, (MouseButtonEventArgs)state);
            }
        }
    }

    /// <summary>
    /// Called when [click].
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
    private void OnClick(object sender, MouseButtonEventArgs e) {
        if (_click != null) {
            if (sender is Control) {
                (sender as Control).Dispatcher.BeginInvoke(_click, sender, e);
            }
        }
    }

    /// <summary>
    /// Called when [double click].
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
    private void OnDoubleClick(object sender, MouseButtonEventArgs e) {
        if (_doubleClick != null) {
            _doubleClick(sender, e);
        }
    }
}

次に、イベントを受信するコントロールで:

MouseClickManager fMouseManager = new MouseClickManager(200);
fMouseManager.Click += new MouseButtonEventHandler(YourControl_Click); 
fMouseManager.DoubleClick += new MouseButtonEventHandler(YourControl_DoubleClick);

他のヒント

 <StackPanel MouseDown="StackPanel_MouseDown">
   <!--stackpanel content-->
    <TextBlock>Hello</TextBlock>
</StackPanel>

その後、イベントハンドラーで:

 private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ClickCount >= 2)
        { 
            string hello; //only hit here on double click  
        }
    }

動作するはずです。 StackPanelをシングルクリックするとイベントがヒットすることに注意してください(ただしifチェックは失敗します)。

...年後。 @MoominTrollのソリューションは完全に受け入れられます。別のオプションは、ダブルクリックイベントをサポートするコンテンツコントロールでスタックパネルをラップすることです。

<ContentControl MouseDoubleClick="DoubleClickHandler" >
    <StackPanel>

    </StackPanel>
</ContentControl>

別のオプションは、StackElementのInputBindingにMouseBindingを追加し、次にMouseBindingによってアクティブ化されるCommandBindingを追加することです。全体として、これは強力な参照によって引き起こされるメモリリークの問題を回避するため、イベントベースのメカニズムよりも優れたプラクティスです。また、コマンドロジックを表現から分離することもできます。

そうは言っても、それほど単純ではなく、イベントにアタッチすることは素晴らしい近道になります。

言うまでもなく、stackpanelの背景を少なくとも透明にするか、「背景」をクリックしたときにマウスクリックヒットテストでキャッチされないようにします。ヒット検出により、ヌルの背景がスキップされます。

同様の問題がありました(シングルクリックイベントに対応し、ダブルクリックイベントの場合は追加の作業を行います)。この方法で問題を解決しました:

1)ラストクリックタイムスタンプを保持する整数を定義および宣言する

int lastClickTimestamp;

2)Window_Loadedメソッドで、以前に宣言された変数を200より大きい数で初期化します

lastClickTimestamp = 1000;

3)マウスボタンハンドラーをスタックパネルに追加します

stackPanel.MouseLeftButtonUp += new MouseButtonEventHandler(stackPanel_MouseLeftButtonUp);

4)次のメソッドを追加

void stackPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (e.Timestamp - lastClickTimeStamp < 200)
        {
            //double click
        }
        lastClickTimeStamp = e.Timestamp;

        //single click
    }

このコードは、シングルクリックイベントとダブルクリックイベントを別々に検出する必要がある場合は役に立ちません。この状況はもう少し複雑になりますが、間違いなく解決できます。

WPF DispatcherTimer を使用して完全な回答。リソースの詰まりを防ぐために、オンデマンドでタイマーを作成し、完了したら切断します。

C#:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

public partial class MainWindow : Window
{
    DispatcherTimer dt;

    bool clear_timer()
    {
        if (dt == null)
            return false;
        dt.Tick -= _single_click;
        dt = null;
        return true;
    }

    private void _click(Object sender, MouseButtonEventArgs e)
    {
        if (clear_timer())
            Debug.Print("double click");
        else
            dt = new DispatcherTimer(
                        TimeSpan.FromMilliseconds(GetDoubleClickTime()),
                        DispatcherPriority.Normal,
                        _single_click,
                        Dispatcher);
    }

    void _single_click(Object sender, EventArgs e)
    {
        clear_timer();
        Debug.Print("single click");
    }

    public MainWindow() { InitializeComponent(); }

    [DllImport("user32.dll")]
    static extern uint GetDoubleClickTime();
 };

XAML:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Horizontal"
                Background="AliceBlue"
                Width="100"
                Height="100"
                MouseLeftButtonDown="_click" />
</Window>

これを行う簡単な解決策があります。

StackPanelのイベントPreviewMouseLeftDown(たとえば)で、MouseButtonEventArgs.ClickCountプロパティの値が2であるかどうかを確認できます。 1 =シングルクリック 2 =ダブルクリック

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top