Reputation: 6147
I have two questions here regarding a wpf C# project.
PreviewMouseMove += OnPreviewMouseMove;
as seen in the code below. 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();
}
}
Upvotes: 0
Views: 200
Reputation: 152556
What is this snippet doing?
It's assigning a handler to the window's PreviewMouseMove
event
how can I essentially apply all these MouseEvents to each control of type in my window?
You already know how to find all of the controls - so just loop through and assign the handler:
foreach (NumericSpinnerControl spinner in FindVisualChildren<NumericSpinnerControl>(this))
{
// do something here
spinner.MouseLeave = OnMouseLeave;
spinner.PreviewMouseUp = OnPreviewMouseUp;
spinner.PreviewMouseMove = OnPreviewMouseMove;
}
Note that you probably want to change spinnerControl
to sender
in your event handler to you're affecting the control that initiated the event rather than referencing a specific control.
Upvotes: 1