Home > Software design >  WPF ComboBox KeyUp Event for all comboboxes
WPF ComboBox KeyUp Event for all comboboxes

Time:11-29

i have a WPF Application with 50 comboboxes. When i started to write this application a month ago, i forgot to add a KeyUp event to all comboboxes... Is there a way of adding this event without going to each comboboxes and write xaml code ?

 <ComboBox x:Name="Actif_Vent_CB" Grid.Column="1"
                              SelectionChanged="Actif_Vent_CB_SelectionChanged"
                              KeyUp="Actif_Vent_CB_KeyUp"/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

 private void Actif_Vent_CB_KeyUp(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            default:
                break;
            case Key.Delete:
            case Key.Back:
                ((ComboBox)sender).SelectedIndex = -1;
                break;
        }
    }

With a Dictionary ?? or something else ?? Thank you for your help

CodePudding user response:

You can traverse through the layout one by one and check if the element is ComboBox and assign event listeners to them.

Call the following method in the Loaded event of your window and pass current window as visual.

public void SetEventToComboBox(Visual myVisual)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i  )
        {
            // Retrieve child visual at specified index value.
            Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);

            // Do processing of the child visual object.
            if (childVisual is ComboBox)
            {
                ((ComboBox)childVisual).KeyUp  = Actif_Vent_CB_KeyUp;
            }
            // Enumerate children of the child visual object.
            SetEventToComboBox(childVisual);
        }
    }

Source: MSDN Documentation

  •  Tags:  
  • wpf
  • Related