【问题标题】:stackpanel highlight on mouse over from code behind鼠标悬停在后面的代码上时堆栈面板突出显示
【发布时间】:2012-04-17 11:52:24
【问题描述】:

从后面的代码中,我可以为我的 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);

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

【问题讨论】:

  • 钩住鼠标事件并改变背景颜色?
  • 您在代码隐藏而不是 XAML 中这样做有什么原因吗?

标签: c# wpf xaml custom-controls stackpanel


【解决方案1】:

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

【讨论】:

  • 非常好的答案正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多