2011-02-08 43 views
0

我的自定義控件使用ScrollViewer,我想確定何時用戶按下水平滾動增量按鈕,而控件已經滾動到水平最大值。一種爲WPF ScrollViewer控件獲取「按鈕按下事件」的方法

查看器包含一個畫布,如果用戶試圖用按鈕滾動超過其範圍,畫布將延伸。

ScrollViewer似乎沒有任何與按鈕有關的事件,ScrollChanged本身沒有用處,因爲它在條形圖的範圍內不會觸發。

.net反射器還沒有產生太多的用途。我能得到的最接近的是爲mouseLeftButtonDown添加一個事件處理程序,我可以看到查看者狀態,但不知道如何確定鼠標事件是否來自按鈕。

任何人都可以想辦法做到這一點?

回答

1

您可以嘗試通過VisualTree獲取控件的按鈕,並將處理程序附加到其單擊事件。

編輯:我寫了一個擴展方法,通過通路越來越可視化樹的項目:

public static class ExtensionMethods 
{ 
    public static DependencyObject GetVisualChildFromTreePath(this DependencyObject dpo, int[] path) 
    { 
     if (path.Length == 0) return dpo; 
     List<int> newPath = new List<int>(path); 
     newPath.RemoveAt(0); 
     return VisualTreeHelper.GetChild(dpo, path[0]).GetVisualChildFromTreePath(newPath.ToArray()); 
    } 
} 

如果您ScrollViewer被稱爲SV你應該能夠得到這樣的按鈕:

RepeatButton button1 = sv.GetVisualChildFromTreePath(new int[] { 0, 2, 0, 0 }) as RepeatButton; //Up 
RepeatButton button2 = sv.GetVisualChildFromTreePath(new int[] { 0, 2, 0, 2 }) as RepeatButton; //Down 
RepeatButton button3 = sv.GetVisualChildFromTreePath(new int[] { 0, 3, 0, 0 }) as RepeatButton; //Left 
RepeatButton button4 = sv.GetVisualChildFromTreePath(new int[] { 0, 3, 0, 2 }) as RepeatButton; //Right 

注意:僅當相應的scollbar啓用時才存在按鈕。通過使用其他數據類型,擴展方法可能在性能方面得到改進。

+0

非常感謝。我添加了一個處理程序到我的ScrollViewers Loaded事件中,該事件找到了horiztonal ScrollBar(一旦初始化),然後使用適當的命令(LineRight)從此按鈕。然後,我爲Click事件添加一個處理程序,它完美地工作。 – sebf 2011-02-08 12:55:46