0
我不想創建新的事件。我需要創建一個可選擇淡入或淡出的畫布控件,具體取決於鼠標是否在其上。下面的代碼可能解釋了我想要做的比我能做得更好。如何處理我的自定義控件中的事件?
private Storyboard fadeInStoryboard;
private Storyboard fadeOutStoryboard;
public FadingOptionPanel()
{
InitializeComponent();
}
public static readonly DependencyProperty FadeEnabledProperty =
DependencyProperty.Register("IsFadeEnabled", typeof(bool), typeof(FadingOptionPanel), new FrameworkPropertyMetadata(true,
OnFadeEnabledPropertyChanged,
OnCoerceFadeEnabledProperty));
public bool IsFadeEnabled
{
get
{
return (bool)GetValue(FadeEnabledProperty);
}
set
{
SetValue(FadeEnabledProperty, value);
}
}
private static void OnFadeEnabledPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
}
private static object OnCoerceFadeEnabledProperty(DependencyObject sender, object data)
{
if (data.GetType() != typeof(bool))
{
data = true;
}
return data;
}
private void FadingOptionPanel_MouseEnter(object sender, MouseEventArgs e)
{
if (IsFadeEnabled)
{
fadeInStoryboard.Begin(this);
}
}
private void FadingOptionPanel_MouseLeave(object sender, MouseEventArgs e)
{
if (IsFadeEnabled)
{
fadeOutStoryboard.Begin(this);
}
}
private void FadingOptionsPanel_Loaded(object sender, RoutedEventArgs e)
{
//Initialize Fade In Animation
DoubleAnimation fadeInDoubleAnimation = new DoubleAnimation();
fadeInDoubleAnimation.From = 0;
fadeInDoubleAnimation.To = 1;
fadeInDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.5));
fadeInStoryboard = new Storyboard();
fadeInStoryboard.Children.Add(fadeInDoubleAnimation);
Storyboard.SetTargetName(fadeInDoubleAnimation, this.Name);
Storyboard.SetTargetProperty(fadeInDoubleAnimation, new PropertyPath(Canvas.OpacityProperty));
//Initialize Fade Out Animation
DoubleAnimation fadeOutDoubleAnimation = new DoubleAnimation();
fadeOutDoubleAnimation.From = 1;
fadeOutDoubleAnimation.To = 0;
fadeOutDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.2));
fadeOutStoryboard = new Storyboard();
fadeOutStoryboard.Children.Add(fadeOutDoubleAnimation);
Storyboard.SetTargetName(fadeOutDoubleAnimation, this.Name);
Storyboard.SetTargetProperty(fadeOutDoubleAnimation, new PropertyPath(Canvas.OpacityProperty));
}
我原本是使用用戶控件,而不是一個自定義的控件中此代碼之前,我發現用戶控件不支持的內容。
謝謝。但是,我收到一個錯誤「'''名稱不能在'Minimalistic_Writer.FadingCanvas'的名稱範圍中找到。」在「fadeInStoryboard.Begin(this);」 – Justin 2010-03-20 23:43:58
我的猜測是,在你的Loaded處理程序中,this.Name返回null。嘗試設置Target屬性而不是TargetName,例如'Storyboard.Target = this;'。 – itowlson 2010-03-21 00:26:43
非常感謝! – Justin 2010-03-21 00:49:56