2010-05-30 29 views
3

我有一个有编程方式添加的动态图像数量的堆叠面板,有没有一种方法可以在这些图像上以编程方式设置悬停/点击效果。我希望图片在点击时“发光”。我如何在Silverlight中做到这一点?我注意到了Image.Effect属性,但我不确定如何使用它。从代码隐藏中添加图片silverlight hovereffect

回答

2

你需要做的是创建一个新的用户控件,其中的图像控件与视觉状态连接在一起。这样,您可以动态地将usercontrol添加到堆栈面板,并调用动画,而不必通过主应用中的事件附加它们。

我在Image.Effect上使用DropShadowEffect创建了一个脉动动画。

例如,这是你的用户控件中:

XAML

<VisualStateManager.VisualStateGroups> 
     <VisualStateGroup x:Name="ImageState"> 
      <VisualState x:Name="NormalImageState"> 
       <Storyboard> 
        <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)" Storyboard.TargetName="image1" d:IsOptimized="True"/> 
       </Storyboard> 
      </VisualState> 
      <VisualState x:Name="GlowingImageState"> 
       <Storyboard AutoReverse="True"> 
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)" Storyboard.TargetName="image1"> 
         <EasingDoubleKeyFrame KeyTime="0" Value="0"/> 
         <EasingDoubleKeyFrame KeyTime="0:0:1" Value="20"/> 
         <EasingDoubleKeyFrame KeyTime="0:0:2" Value="0"/> 
        </DoubleAnimationUsingKeyFrames>       
       </Storyboard> 
      </VisualState> 
     </VisualStateGroup> 
    </VisualStateManager.VisualStateGroups> 

    <Image Name="image1" MouseEnter="image1_MouseEnter" MouseLeave="image1_MouseLeave" > 
     <Image.Effect> 
      <DropShadowEffect Color="Red" BlurRadius="0" ShadowDepth="0"/> 
     </Image.Effect> 
    </Image> 

C#

public ImageSource ImageSource 
    { 
     get; 
     set 
     { 
      image1.Source = value; 
     } 
    } 
    private void image1_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) 
    { 
     VisualStateManager.GoToState(this, "GlowingImageState", true); 
    } 

    private void image1_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e) 
    { 
     VisualStateManager.GoToState(this, "NormalImageState", true); 
    } 

然后你就可以在这个用户控件添加到您的堆叠面板像这样:

MyUC uc= new MyUC(); //control we just created 
uc.ImageSource = sourceOfImg; //the source of the intended image 
myStack.Children.Add(uc); //adding it to the stackpanel. 

告诉我我这个工作。

+0

感谢您的建议。我去了,实际上改变了ffecttype,但用户控制方法是我拿的! – Jakob 2010-05-30 22:24:16