Oleg

Oleg

  • NA
  • 5
  • 0

RoutedEvent from Window to UserControl

Sep 9 2008 10:12 AM
Hello,

I have constructed a Window2 with a stack panel, inside the stack panel there is a user control and a list box. After I start the application the window should route any keyboard event to the user control. For this purpose I implemented in Window2 OnPreviewKeyDown(KeyEventArgs e) which raise a custom KeyboardRoutedEvent from user control. The user control contains information about the KeyboardRoutedEvent. Additionally,  in the contructor a handler is added to the user control. But, the window does not route the event.

Has somebody any idea how to solve this problem?? Thank you in advance!

Sergej

public partial class Window2 : Window 
    {  
 
        private ListBox listBox; 
        private UserControl userControl; 
 
        public Window2(UserControl2 userControl) 
        { 
            this.userControl = userControl; 
 
            this.Title = "Ring elements"
            this.Height = 350; 
            this.Width = 300; 
            this.Background = Brushes.WhiteSmoke; 
 
            //Viewbox viewbox = new Viewbox(); 
            //viewbox.Child = userControl; 
 
            listBox = new ListBox(); 
            StackPanel stackPanel = new StackPanel(); 
 
            //this.Content = viewbox; 
            this.Content = stackPanel; 
            stackPanel.Children.Add(userControl); 
            stackPanel.Children.Add(listBox); 
 
        } 
 
        protected override void OnPreviewKeyDown(KeyEventArgs e) 
        { 
            MessageBox.Show("Window2"); 
 
            // Raise the event 
            this.RaiseEvent(new RoutedEventArgs(UserControl2.KeyboardRoutedEvent, this)); 
 
            //this.Title= "Source = " + e.Source.GetType. 
 
        } 
 
    } 
 
public class UserControl2 : UserControl  
    public UserControl2()  
    { 
         //..... 
        this.AddHandler(UserControl2.KeyboardRoutedEvent,        new           RoutedEventHandler(RoutedEvent_Raised)); 
    } 
 
    static UserControl2()  
    { 
         UserControl2.KeyboardRoutedEvent = EventManager.RegisterRoutedEvent("RoutedKeyDown"
                                                                         RoutingStrategy.Tunnel, 
                                                                               typeof(RoutedEventHandler), 
                                                                               typeof(UserControl2)); 
    } 
 
    public static readonly RoutedEvent KeyboardRoutedEvent; 
 
        public event RoutedEventHandler RoutedKeyDown 
        { 
            add { AddHandler(UserControl2.KeyboardRoutedEvent, value); } 
            remove { RemoveHandler(UserControl2.KeyboardRoutedEvent, value); } 
        } 
 
        private void RoutedEvent_Raised(object sender, RoutedEventArgs e) 
        { 
            MessageBox.Show("Superb!"); 
        } 


Answers (2)