我需要制作一个功能,当鼠标进入和离开按钮区域时显示和隐藏标签。
我开始为每个按钮单独做,但是因为会有超过 5 个代码变得重复,所以有必要制作一个功能。我刚开始使用 C#,所以我有点迷茫。
每个按钮看起来像这样:
private void BtnP1_MouseEnter(object sender, EventArgs e)
{
LblP1.Visible = true;
}
private void BtnP1_MouseLeave(object sender, EventArgs e)
{
LblP1.Visible = false;
}
标签设置为 visible = false 所以当鼠标进入按钮时它会显示链接的标签并在它离开时隐藏。
一个方法可以处理任意多的事件。在设计器中,选择多个
Buttons
,例如通过 Ctrl+单击,然后打开 Properties 窗口并单击 Events 按钮。然后,您可以通过双击事件为所有控件生成一个事件处理程序方法,或者从下拉列表中选择现有方法。
如果您需要引用引发事件的实际控件 - 在这种特殊情况下似乎不需要 - 那么您可以使用
sender
参数来实现,该参数始终是对引发事件的对象的引用。
你有很多解决方案:
您可以创建一个样式,而不是为每个按钮定义事件 MouseEnter/Leave。
要将标签与其按钮链接起来,例如我选择了按钮的名称
bxx
和标签lxx
。因此,在处理程序中,您可以使用 FindName
魔术方法轻松找到链接到其按钮的标签名称。
视图:
<Window x:Class="LivechartTest.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LivechartTest.Views"
mc:Ignorable="d"
Title="MainView" Height="600" Width="800">
<Window.Resources>
<Style x:Key="CustomButton" TargetType="Button">
<EventSetter Event="MouseEnter" Handler="But_MouseEnter"/>
<EventSetter Event="MouseLeave" Handler="But_MouseLeave"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</Window.Resources>
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" >
<Button x:Name="b01" Style="{StaticResource CustomButton}" Background="Gray" Content="b01" Margin="10"/>
<Label x:Name="l01" Content="l01" Margin="10"/>
<Button x:Name="b02" Style="{StaticResource CustomButton}" Background="Yellow" Content="b02" Margin="10"/>
<Label x:Name="l02" Content="l02" Margin="10"/>
</StackPanel>
<StackPanel Orientation="Vertical">
<Button x:Name="b11" Style="{StaticResource CustomButton}" Background="AliceBlue" Content="b11" Margin="10"/>
<Label x:Name="l11" Content="l11" Margin="10"/>
<Button x:Name="b12" Style="{StaticResource CustomButton}" Background="Orange" Content="b12" Margin="10"/>
<Label x:Name="l12" Content="l12" Margin="10"/>
</StackPanel>
</StackPanel>
</Grid>
</Window>
背后的代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace LivechartTest.Views
{
/// <summary>
/// Logique d'interaction pour MainView.xaml
/// </summary>
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
}
private void But_MouseEnter(object sender, MouseEventArgs e)
{
var button = sender as Button;
var myLabel = (Label)this.FindName(button.Name.Replace("b" ,"l"));
myLabel.Visibility = Visibility.Hidden;
}
private void But_MouseLeave(object sender, MouseEventArgs e)
{
var button = sender as Button;
var myLabel = (Label)this.FindName(button.Name.Replace("b", "l"));
myLabel.Visibility = Visibility.Visible;
}
}
}