WPF圖標特殊效果實現(xiàn)方法
WPF開發(fā)工具的用途主要是體現(xiàn)在各種圖形界面的顯示方面。那么在使用的過程中,其中有很多技巧值得我們?nèi)ド钊胙芯?。本篇將要實現(xiàn)圖標的兩個效果:1. 顯示圖標標簽,2. 圖標模糊效果。#t#
在上一篇中提到Image沒有HTML < img>的Title屬性(在MSDN中也沒找到類似的屬性),所以本篇將自行制作一個標簽,它的功能是當鼠標移動到圖標上方時會顯示該圖標的Tag說明,并且該WPF圖標模糊顯示。
1. 在Home < Image>中加入MouseEnter和MouseLeave事件。
- < Image Source="image/home.png"
- Width="110" Height="110"
- Tag="My Home"Canvas.Left="30"
Canvas.Top="20" - Cursor="Hand"
- MouseEnter="Image_BlurEffect_MouseEnter"
- MouseLeave="Image_BlurEffect_MouseLeave">
- < /Image>
2. 事件加好了,就要為添加內(nèi)容了。先看Image_BlurEffect_MouseEnter事件:
- private void Image_BlurEffect_
MouseEnter(object sender,
MouseEventArgs e)- {
- //將sender定義為Image對象
- Image image = sender as Image;
- //創(chuàng)建模糊BlurEffect對象
- BlurEffect newBlurEffect =
new BlurEffect();- //設定模糊效果值Radius
- newBlurEffect.Radius = 5;
- //為Image添加Blur效果
- image.Effect = newBlurEffect;
- //將Image Tag內(nèi)容傳給imageTitle
Textblock- imageTitle.Text = " " +
image.Tag.ToString() +" ";- //將imageTitle的Border設置為可見
- imageTitleBorder.Visibility =
Visibility.Visible;- //調(diào)整imageTitleBorder的Canvas位置,
使其在圖標下方顯示- Canvas.SetLeft(imageTitleBorder,
Canvas.GetLeft(image)+ image.
Width / 2 - 15);- Canvas.SetTop(imageTitleBorder, 125);
- }
- private void Image_BlurEffect_
MouseLeave(object sender,
MouseEventArgs e)- {
- Image image = sender as Image;
- BlurEffect newBlurEffect =
new BlurEffect();- newBlurEffect.Radius = 0;
- image.Effect = newBlurEffect;
- imageTitleBorder.Visibility =
Visibility.Collapsed;- }
可以使用ToolTipService。經(jīng)過測試使用ToolTip可以實現(xiàn)標簽的功能(代碼如下),而且也不用預設WPF圖標顯示效果,但是沒法通過Canvas設定其位置,大家可以都學習一下。
- XAML:
- < Image Source="image/home.png"
Width="110" Height="110"- Tag="My Home" Canvas.Left="30"
Canvas.Top="20"- MouseEnter="Image_BlurEffect_
MouseEnter"- MouseLeave="Image_BlurEffect_
MouseLeave"- Cursor="Hand">
- < Image.ToolTip>
- < TextBlock>My Home< /TextBlock>
- < /Image.ToolTip>
- < /Image>
C#代碼自然就簡單多了:
- private void Image_BlurEffect_
MouseEnter(object sender,
MouseEventArgs e)- {
- Image image = sender as Image;
- BlurEffect newBlurEffect =
new BlurEffect();- newBlurEffect.Radius = 5;
- image.Effect = newBlurEffect;
- }
上面這些方法介紹的就是WPF圖標顯示效果的實現(xiàn)。