[英]How to switch on the mouse over effect of a button programmatically?
我的wpf中的按鈕有問題。 如果我將鼠標移到按鈕上,它將變為默認的淺藍色,但我在按鈕中有一個圖像,因此當鼠標在那里時圖像會隱藏。
我已經看到了一些解決方案,但它們是在XAML代碼中制作的。 我以編程方式創建了按鈕,因此無效。 如果我沒有光標,最后按下的按鈕也會閃爍。 問題是一樣的。 所以我需要C#代碼而不是xaml代碼。
有任何想法嗎? :)
閃爍按鈕和藍色突出顯示顏色是按鈕默認樣式的一部分,要更改它,您需要覆蓋默認樣式。 我建議你在XAML中創建你的風格,然后以編程方式分配它。 您可以在此處獲取默認按鈕樣式,然后查看有關如何以編程方式設置樣式的帖子 。
更新:它似乎對我有用,這就是我所做的:
在后面的代碼中有問題地創建按鈕並設置樣式:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.