Question

I am creating a common animation function for all WPF Controls like TextBlock, Grid, TextBox... like below

private void animateFadeOut(*** displayObj)
{
    displayObj.Opacity = 1;
    System.Windows.Media.Animation.DoubleAnimation fadingAnimation = new System.Windows.Media.Animation.DoubleAnimation();
    fadingAnimation.From = 1;
    fadingAnimation.To = 0;
    fadingAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
    displayObj.BeginAnimation(TextBlock.OpacityProperty, fadingAnimation);
}

So I just want to know that which class should i write in place of ***. I tried UserControl, Object but I got issue in UserControl for Converting TextBlock or Grid to UserControl. And in Object, there is no Opacity value. So what is the best way to handle this?

Was it helpful?

Solution

Highest common ancestor for Grid, TextBlock and TextBox is FrameworkElement but if you want to animate Opacity then it's property of even higher class UIElement

private void animateFadeOut(UIElement displayObj)
{
    displayObj.Opacity = 1;
    System.Windows.Media.Animation.DoubleAnimation fadingAnimation = new System.Windows.Media.Animation.DoubleAnimation();
    fadingAnimation.From = 1;
    fadingAnimation.To = 0;
    fadingAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
    displayObj.BeginAnimation(UIElement.OpacityProperty, fadingAnimation);
}

OTHER TIPS

Though not sure if your code would work for Grid also, but the class you are looking for is "UIElement"

You can check their Inheritance Hierarchy on MSDN. E.g. for Grid:

Inheritance Hierarchy
System.Object 
  System.Windows.Threading.DispatcherObject
    System.Windows.DependencyObject
      System.Windows.Media.Visual
        System.Windows.UIElement
          System.Windows.FrameworkElement
            System.Windows.Controls.Panel
              System.Windows.Controls.Grid
                System.Windows.Controls.Primitives.SelectiveScrollingGrid

They all under System.Windows.Controls namespace, but I found out that use FrameworkElement is better (as in my case I need to invoke BringIntoView()). You could check the hierarchy and decide by yourself. But AFAIK, FrameworkElement should be used as it provides everything (property and method) you may need to get access to in your situation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top