Search code examples
c#wpfxamlcustom-controlsstackpanel

stackpanel highlight on mouse over from code behind


From code behind I can set some generic things to my groupbox and stackpanel but I cant find anything on how to highlight a stack panel from code behind.

        GroupBox groupbox = new GroupBox(); 
        groupbox.Header = String.Format(node.Element("StudentID").Value); 
        groupbox.Width = 100; 
        groupbox.Height = 100; 
        groupbox.Margin = new Thickness(1); 

        TextBlock textBlock = new TextBlock(); 
        textBlock.Text = String.Format(node.Element("FirstName").Value + " " + (node.Element("LastName").Value)); 
        textBlock.TextAlignment = TextAlignment.Center; 

        TextBlock textBlock1 = new TextBlock(); 
        textBlock1.Text = (DateTime.Parse(node.Element("TimeAdded").Value)).ToString("d"); 
        String.Format("{0:d/M/yyyy}", DateTime.Parse(node.Element("TimeAdded").Value)); 
        textBlock1.TextAlignment = TextAlignment.Center; 
        textBlock1.VerticalAlignment = VerticalAlignment.Bottom; 

        StackPanel stackPanel = new StackPanel(); 
        stackPanel.Children.Add(groupbox); 

        stackPanel.Children.Add(textBlock); 
        stackPanel.Children.Add(textBlock1); 
        stackPanel.Margin = new Thickness(5);

I wish to on mouse over create a highlight of a ligher grey, also this code belongs to a customcontrol.


Solution

  • Add handlers for the MouseEnter and MouseLeave events:

    public MainWindow()
    {
        InitializeComponent();
    
        StackPanel stackpanel = new StackPanel(); 
        stackpanel.MouseEnter += new MouseEventHandler(stackpanel_MouseEnter);
        stackpanel.MouseLeave += new MouseEventHandler(stackpanel_MouseLeave);
    }
    
    void stackpanel_MouseLeave(object sender, MouseEventArgs e)
    {
        StackPanel stackpanel = (StackPanel)sender;
        stackpanel.Background = Brushes.Transparent;
    }
    
    void stackpanel_MouseEnter(object sender, MouseEventArgs e)
    {
        StackPanel stackpanel = (StackPanel)sender;
        stackpanel.Background = Brushes.LightGray;
    }