【问题标题】:How to switch on the mouse over effect of a button programmatically?如何以编程方式打开按钮的鼠标悬停效果?
【发布时间】:2012-04-28 19:45:05
【问题描述】:

我对 wpf 中的按钮有疑问。如果我将鼠标移到按钮上,它会变成默认的浅蓝色,但我在按钮中有一个图像,所以当鼠标在那里时图像会隐藏。

我已经看到了一些解决方案,但它们是在 XAML 代码中制作的。我以编程方式创建了我的按钮,所以它不起作用。如果我没有光标,最后按下的按钮也会闪烁。问题是一样的。所以我需要 C# 代码而不是 xaml 代码。

有什么想法吗? :)

【问题讨论】:

    标签: c# wpf button


    【解决方案1】:

    闪烁的按钮和蓝色突出显示颜色是按钮默认样式的一部分,要更改它,您需要覆盖默认样式。我建议在 XAML 中创建您的样式,然后以编程方式分配它。您可以获取默认按钮样式here,然后查看this post 了解如何以编程方式设置样式。

    更新: 它似乎对我有用,这就是我所做的:

    在后面的代码中创建按钮有问题并设置样式:

    public MainWindow()
    {
        InitializeComponent();
    
        Bitmap bitMap = new Bitmap(@"\path\to\image.png");
        MemoryStream ms = new MemoryStream();
        bitMap.Save(ms, ImageFormat.Png);
        ms.Seek(0,SeekOrigin.Begin);
    
        BitmapImage bitMapImage = new BitmapImage();
        bitMapImage.BeginInit();
        bitMapImage.StreamSource = ms;
        bitMapImage.EndInit();
    
        Image image = new Image();
        image.Source = bitMapImage;
        image.Height = 100;
    
        Button button = new Button();
        button.Height = 200;
        button.Width = 200;
        button.Content = image;
        button.Style = button.Style = (Style)FindResource("myButtonStyle");
    
        myGrid.Children.Add(button);
     } 
    

    通过复制和粘贴 microsoft 提供的按钮样式并修改为您想要的行为,在 XAML 中创建样式。为了禁用鼠标悬停效果,我注释掉了 <VisualState x:Name="MouseOver"> ... </VisualState>

    部分
    <Style x:Key="myButtonStyle" TargetType="Button">
        <!-- Style copied from MSDN Button Style page -->
        <!-- Remove or comment out <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}" /> -->
        <!-- Remove or comment out <VisualState x:Name="MouseOver> ... </VisualState>
        <!-- Change colors to your liking or set to Transparent to not show color -->
        ....
    </Style>
    

    【讨论】:

    • 好的。我已经尝试过您的解决方案,但它并没有达到我想要的效果。按钮中的文本样式发生了变化,但是当光标在它上面时,它变成了相同的浅蓝色。所以我的图片没有显示出来。
    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2013-06-15
    • 2012-04-27
    • 1970-01-01
    • 2011-04-20
    相关资源
    最近更新 更多