在Silverlight 2 beta2中,开发一个自定义控件ActionSpotButton,该控件包含一个背景矩形rectBackground和一个按钮hotButton。想当用户鼠标移动到Button上时改变背景矩形的颜色。
generic.xaml文件内容如下:
- <Style TargetType="local:ActionSpotButton">
- <Setter Property="IsEnabled" Value="True" />
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="local:ActionSpotButton">
- <Canvas x:Name="RootElement" Background="WhiteSmoke">
- <vsm:VisualStateManager.VisualStateGroups>
- <vsm:VisualStateGroup x:Name="CommonStates">
- <vsm:VisualState x:Name="Normal" >
- <Storyboard>
- <DoubleAnimation BeginTime="00:00:00" From="0" To="0.5" Duration="0" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.Opacity)" />
- </Storyboard>
- </vsm:VisualState>
- <vsm:VisualState x:Name="MouseOver1">
- <Storyboard>
- <DoubleAnimation BeginTime="00:00:00" From="0" To="1" Duration="0" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.Opacity)" />
- </Storyboard>
- </vsm:VisualState>
- </vsm:VisualStateGroup>
- </vsm:VisualStateManager.VisualStateGroups>
- <Canvas x:Name="HotArea">
- <Rectangle Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Fill="Green" x:Name="image" />
- <Button RenderTransformOrigin="0,0" Content="Hot Button" Cursor="Hand" x:Name="HotButton" Opacity="0.5" Canvas.Left="20" Canvas.Top="20" Width="160" Height="160" />
- </Canvas>
- </Canvas>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
如果其中HotButton的范围与rectBackground重合,则鼠标移动到hotButton上虽然出发MouseEnter事件,但不会使得rectBackground改变颜色。严格的说,Mouse 必须先经过/滑动过Control中除hotButton以外的区域,然后再滑动到hotButton上时才会使rectBackground改变颜色。
在这个控件中,如果要想hotButton和rectBackground重合,而又要使得鼠标移动到hotButton上rectBackground改变颜色,可以将Control的大小扩大,且将rectBackground和hotButton的位置向右下方做同等位移(位移大小10~20,是否产生效果还与鼠标移动的速度有关)。
- public override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
- // remove events
- if (_hotButton != null)
- {
- _hotButton.Click -= new RoutedEventHandler(_hotButton_Click);
- _hotButton.MouseEnter -= new MouseEventHandler(_hotButton_MouseEnter);
- _hotButton.MouseLeave -= new MouseEventHandler(_hotButton_MouseLeave);
- }
- _hotButton = this.GetTemplateChild("HotButton") as Button;
- image = this.GetTemplateChild("image") as Rectangle;
- rootElemnt = this.GetTemplateChild("HotArea") as Canvas;
- // add events
- if (_hotButton != null)
- {
- _hotButton.Click += new RoutedEventHandler(_hotButton_Click);
- _hotButton.MouseEnter += new MouseEventHandler(_hotButton_MouseEnter);
- _hotButton.MouseLeave += new MouseEventHandler(_hotButton_MouseLeave);
- }
- this.SetValue(Canvas.LeftProperty, -20.0);
- this.SetValue(Canvas.TopProperty, -20.0);
- this.Width += 40.0;
- this.Height += 40.0;
- rootElemnt.SetValue(Canvas.LeftProperty, 20.0);
- rootElemnt.SetValue(Canvas.TopProperty, 20.0);
- }