stackpanel突出显示鼠标悬停在代码后面

时间:2012-04-17 03:14:09

标签: c# wpf xaml custom-controls stackpanel

从代码背后我可以为我的groupbox和stackpanel设置一些通用的东西,但是我找不到任何关于如何从代码背后突出显示堆栈面板的东西。

        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);

我希望鼠标悬停创建一个灰色的高亮显示,此代码也属于自定义控件。

1 个答案:

答案 0 :(得分:4)

为MouseEnter和MouseLeave事件添加处理程序:

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;
}