我在这里有两个关于wpf C#项目的问题。
PreviewMouseMove += OnPreviewMouseMove;
,如下面的代码所示。 public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PreviewMouseMove += OnPreviewMouseMove;
PreviewMouseLeftButtonUp += OnPreviewMouseUp;
MouseLeave += OnMouseLeave;
}
private void OnMouseLeave(object sender, MouseEventArgs e)
{
spinnerControl.StopDragCapture(null);
}
private void OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
{
spinnerControl.StopDragCapture(e);
}
private void OnPreviewMouseMove(object sender, MouseEventArgs e)
{
spinnerControl.UpdateOnDragMove(e);
}
}
public partial class MainWindow : Window
{
// Enumerate all the descendants of the visual object.
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
private void InitNumericSpinners()
{
foreach (NumericSpinnerControl spinner in FindVisualChildren<NumericSpinnerControl>(this))
{
// do something here
// spinner (add OnMouseLeave event)
// spinner (add OnPreviewMouseUp event)
// spinner (add OnPreviewMouseMove event)
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
InitNumericSpinners();
}
}
答案 0 :(得分:1)
这段代码在做什么?
为窗口分配处理程序的PreviewMouseMove
事件
如何将所有这些MouseEvent实际应用于窗口中的每个类型控件?
您已经知道如何查找所有控件 - 所以只需循环并分配处理程序:
foreach (NumericSpinnerControl spinner in FindVisualChildren<NumericSpinnerControl>(this))
{
// do something here
spinner.MouseLeave = OnMouseLeave;
spinner.PreviewMouseUp = OnPreviewMouseUp;
spinner.PreviewMouseMove = OnPreviewMouseMove;
}
请注意,您可能希望将事件处理程序中的spinnerControl
更改为sender
,以便影响启动事件的控件,而不是引用特定控件。