2010-05-30 30 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