本节是基于第四节的源码基础上进行扩展的源码,故本节源码附带有鼠标右键和全屏功能。
在本节,我们将讲述一个小技巧:使用Popup浮动窗体控件模拟Tip悬浮效果。此技巧的原理是当鼠标移动到某个控件上面的时候会触发MouseMove事件,此时设置Popup控件显示出来。触发此事件时能够获知此时的鼠标坐标位置,我们根据鼠标位置的变化的同时移动Popup控件的HorizontalOffset属性(获取或设置目标原点与弹出项对齐点之间的水平距离)和VerticalOffset(获取或设置目标原点与弹出项对齐点之间的垂直距离)。如果鼠标移出自定义控件,那么设置Popup浮动窗体的IsOpen属性为false隐藏此浮动窗体。
创建一个自定义控件命名为Tipwindow,其XAML代码如下:
< UserControl x:Class = " SLRightMouseButton.Tipwindow "
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 "
mc:Ignorable = d "
d:DesignHeight = 300 " d:DesignWidth = 400 " xmlns:sdk = http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk " >
< Grid x:Name = LayoutRoot " Background = White " >
< Popup x:Name = tip " >
< Grid x:Name = toolTip " Width = 312 " Height = 200 " >
< Grid.Background >
< ImageBrush ImageSource = ./BG.png " ></ ImageBrush >
</ Grid.Background >
< Grid.RowDeFinitions >
< RowDeFinition Height = auto " />
< RowDeFinition />
</ Grid.RowDeFinitions >
< Grid.ColumnDeFinitions >
< ColumnDeFinition Width = " />
</ Grid.ColumnDeFinitions >
< TextBlock Grid.Row = 0 " Grid.Column = " x:Name = mainContent " Foreground = " FontSize = 14 Auto " HorizontalAlignment = Center " Margin = 0 20 0 0 " VerticalAlignment = Top " />
</ Grid >
</ Popup >
</ Grid >
</ UserControl >
<Grid.Background>
<ImageBrush ImageSource="./BG.png"></ImageBrush>
</Grid.Background>
这几句话设置整个Grid的背景图片为当前目录下的BG.png,所以我们也要在项目中引入该文件。再来看看Tipwindow.cs的关键源代码如下:
public void BindControl(UIElement uc)
{
uc.MouseLeave += new MouseEventHandler(ti_MouseLeave);
uc.MouseMove += new MouseEventHandler(ti_MouseMove);
}
void CancelBindControl(UIElement uc)
{
uc.MouseLeave -= new MouseEventHandler(ti_MouseLeave);
uc.MouseMove -= new MouseEventHandler(ti_MouseMove);
}
/// <summary>
鼠标离开自定义控件时,隐藏提示框
</summary> <param name="sender"></param> <param name="e"></param>
private void ti_MouseLeave( object sender,MouseEventArgs e)
{
this .tip.IsOpen = false ;
}
鼠标在自定义控件上移动式时,提示框也跟随移动
void ti_MouseMove( true ;
this .tip.HorizontalOffset = e.GetPosition( null ).X - 158 ;
this .tip.VerticalOffset = e.GetPosition( null ).Y - 202 ;
}
此关键代码中有一个绑定函数BindControl(UIElement uc),让需要获得Tipwindow浮动框的uc控件绑定MouseMove和MouseLeave事件。现在再创建一个新的自定义控件Rect.xaml,并且添加一个IsFlag属性,此属性指示Rect自定义控件是否显示Tipwindow浮动框。XAML代码里面添加一个矩形控件ti,代码如下:
< Rectangle x:Name = " ti " Width = 50 " Height = " RadiusX = 5 " RadiusY = " Fill = YellowGreen " ></ Rectangle >
Rect自定义控件制作好了,在MainPage.xaml.cs文件中,实例化此自定义控件,并且设置其IsFlag属性为True即可看到下面图片的效果了。
MainPage.xaml.cs:
rect.Margin = new Thickness( 250 );
rect.IsFlag = this .LayoutRoot.Children.Add(rect);