• 0

[C#/WPF] Animate a UserControl


Question

Hello gang,

I am learning WPF and I need to animate a UserControl that has been added during runtime

XAML


<Window x:Class="BediaNVMain.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="515" Width="1598" ShowInTaskbar="False" Topmost="True" WindowState="Maximized" WindowStyle="None" Background="#FF001900" xmlns:my="clr-namespace:BediaMenu;assembly=BediaMenu">
<Canvas Name="BediaCanvas"
<Grid Name="BediaGrid" Loaded="BediaGrid_Loaded">
</Grid>
</Canvas>
</Window>
[/CODE]

C# code to add UserControl (BediaMenu.BMenu)

[CODE]
var bmnuBediaMenu = new BediaMenu.BMenu();
bmnuBediaMenu.Margin = new Thickness(40, MenuTop, 40, 20);
bmnuBediaMenu.MenuText = MenuTitle;
bmnuBediaMenu.Height = this.MenuSize;
bmnuBediaMenu.Width = this.ActualWidth - 80;
this.BediaGrid.Children.Add(bmnuBediaMenu);
[/CODE]

I attempted to use the code from this page: http://stackoverflow.com/questions/4214155/wpf-easiest-way-to-move-image-to-x-y-programmatically But when it gets to the last line; story.Begin(this); it errors with this statement: "'BediaMenu' name cannot be found in the name scope of 'BediaNVMain.MainWindow'." I have attempted several options... but with no success.

Any thoughts?

Link to comment
https://www.neowin.net/forum/topic/1051139-cwpf-animate-a-usercontrol/
Share on other sites

Recommended Posts

  • 0
  On 13/01/2012 at 19:46, James Rose said:

I'd love to just use XAML, but the number of menus varies based on the user's screen height and the height of the menu (customizable) so until runtime I do not know how many I will need. I REALLY wish I could know ahead of time, that would make my life SO much easier.

Should work fine either way - this is actually selfcontained XAML in the bmnuBediaMenu UserControl. Meaning, everytime you create an instance of a new bmnuBediaMenu, it'll run this animation on itself. No additional coding on your part.

  • 0

I admit myself irked >.>

  On 13/01/2012 at 19:48, ~Johnny said:

Should work fine either way - this is actually selfcontained XAML in the bmnuBediaMenu UserControl. Meaning, everytime you create an instance of a new bmnuBediaMenu, it'll run this animation on itself. No additional coding on your part.

That's what I thought, but I didn't want to say that and be wrong >.<

  • 0
  On 13/01/2012 at 19:48, ~Johnny said:

Should work fine either way - this is actually selfcontained XAML in the bmnuBediaMenu UserControl. Meaning, everytime you create an instance of a new bmnuBediaMenu, it'll run this animation on itself. No additional coding on your part.

Ah, interesting. (really) I will think it over. Thank you

  On 13/01/2012 at 19:53, articuno1au said:

I admit myself irked >.>

That's what I thought, but I didn't want to say that and be wrong >.<

I always believe it is better to speak up and be wrong than to be silent. But then, I talk too much.

  • 0
  On 13/01/2012 at 19:56, James Rose said:

Ah, interesting. (really) I will think it over. Thank you

Just drop it inside the bmnuBediaMenu UserControl now and see if it works. Should only take a minute :p It should literally be a copy/paste jobbie.

Failing that, there's also another method where you can write the XAML storyboard in a separate file without an animation target, then load then dynamically load in the XAML storyboard in at runtime and set the target to whatever element you want.

  • 0
  On 13/01/2012 at 20:01, ~Johnny said:

Just drop it inside the bmnuBediaMenu UserControl now and see if it works. Should only take a minute :p It should literally be a copy/paste jobbie.

Failing that, there's also another method where you can write the XAML storyboard in a separate file without an animation target, then load then dynamically load in the XAML storyboard in at runtime and set the target to whatever element you want.

I have to deal with something else right now, I will try this out this eve or tomorrow.

Thank you VERY much for your time.

  • 0

Hey peoples,

I have not taken the time to go through this... but I did have a thought. The code I have been talking about has been on the MainWindow, not the UserControl. After Johnny posted some code (which I plan on getting to tomorrow) I came to a realization that maybe any (all?) of this code would work if it was within the control. I was attempting to make it work by affecting the control from the window, not within the control itself.

  • 0


public static void Translate(FrameworkElement e, int X, int Y, int dX, int dY, TimeSpan duration)
{
// Create storyboard
var sb = new Storyboard();

// Create TranslateTransform
TranslateTransform tt2 = new TranslateTransform();
e.RegisterName("TT2", tt2);
e.RenderTransform = tt2;

// Create x Animation
DoubleAnimation aniX = new DoubleAnimation
{
From = X, To = dX, Duration = new Duration(duration)
};

sb.Children.Add(aniX);
Storyboard.SetTargetName(aniX, "TT2");
Storyboard.SetTargetProperty(aniX, new PropertyPath(TranslateTransform.XProperty));

// Create Y Animation
DoubleAnimation aniY = new DoubleAnimation
{
From = Y, To = dY, Duration = new Duration(duration)
};

sb.Children.Add(aniY);
Storyboard.SetTargetName(aniY, "TT2");
Storyboard.SetTargetProperty(aniY, new PropertyPath(TranslateTransform.YProperty));

// Register Storyboard
e.Resources.Add("SB);
sb.Begin();

// Unregister Storyboard (Cleanup)
e.Resources.Remove("SB");
e.UnregisterName("TT2");
}[/CODE]

Tested it myself, seems to work fine with UserControls. Not perfect as it overwrites the RenderTransform with a new TranslateTransform each time you use it (and really it should be using transform groups), but it should work for you.

Doesn't have to be used from inside the UserControl. Works fine from using it within the main window. It's pretty close to my previous code, just this time it registers not to the parent element but itself (I have no idea why I decided to do it to the parent the first time, it was very old code of mine)

You will probably want to add some easing modes to it however. Doesn't really look natural without them (Quadratic EaseIn seems like a good fit?)

  • 0

No problem.

Adding the following to the method and then setting the "EasingFunction" of both DoubleAnimations to it should make it look slightly more natural too. (I've found the EaseOut mode always looks better for animating items into view, and EaseIn for animating out of view)


QuadraticEase ease = new QuadraticEase { EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut };
[/CODE]

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • qBittorrent 5.1.1 by Razvan Serea The qBittorrent project aims to provide a Free Software alternative to µtorrent. qBittorrent is an advanced and multi-platform BitTorrent client with a nice user interface as well as a Web UI for remote control and an integrated search engine. qBittorrent aims to meet the needs of most users while using as little CPU and memory as possible. qBittorrent is a truly Open Source project, and as such, anyone can and should contribute to it. qBittorrent features: Polished µTorrent-like User Interface Well-integrated and extensible Search Engine Simultaneous search in most famous BitTorrent search sites Per-category-specific search requests (e.g. Books, Music, Movies) All Bittorrent extensions DHT, Peer Exchange, Full encryption, Magnet/BitComet URIs, ... Remote control through a Web user interface Nearly identical to the regular UI, all in Ajax Advanced control over trackers, peers and torrents Torrents queueing and prioritizing Torrent content selection and prioritizing UPnP / NAT-PMP port forwarding support Available in ~25 languages (Unicode support) Torrent creation tool Advanced RSS support with download filters (inc. regex) Bandwidth scheduler IP Filtering (eMule and PeerGuardian compatible) IPv6 compliant Available on most platforms: Linux, Mac OS X, Windows, OS/2, FreeBSD qBittorrent 5.1.1 changelog: BUGFIX: Don't interpret wildcard pattern as filepath globbing (glassez) BUGFIX: Fix appearance of search history length spinbox (glassez) BUGFIX: Remove dubious seeding time max value (glassez) BUGFIX: Fix ratio handling (glassez) BUGFIX: Fix compilation with Qt 6.6.0 (glassez) WEBUI: Make General tab text selectable by default (dezza) WEBUI: Add versioning to local preferences (Chocobo1) WEBUI: Make multi-rename search & replace fields use a monospace font (Atk) WEBUI: Fix wrong replacement sequence in IPv6 string (Chocobo1) WEBUI: Fix memory leak (bolshoytoster) WEBUI: Fix path autofill in set location and new category (tehcneko) RSS: Mark matched article as "read" if it refers to a duplicate torrent (glassez) WINDOWS: Update command line help message (KanishkaHalder1771) WINDOWS: NSIS: Don't require agreement on the license page (Chocobo1) LINUX: Fix preview not opening on Wayland (Isak05) LINUX: Add fallback for random number generator (Chocobo1) Download: qBittorrent 5.1.1 | Portable | ~40.0 MB (Open Source) Download: qBittorrent 64-bit installer (qt6) | 41.7 MB Links: qBittorrent Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Linus Torvalds releases a pretty ordinary Linux 6.16-rc3 by Paul Hill Linus Torvalds, the head and founder of the Linux kernel, has announced the release of Linux 6.16-rc3. This release comes with fixes for new features that were introduced during the merge window several weeks ago, and for old features where issues have been detected or improvements need to be made. If you remember last week, Torvalds said that rc2 seemed smaller than usual, putting it down to people going on vacation. He said this week’s rc3 seems to be in the usual ballpark for this time of the cycle, so everything looks “entirely normal.” In terms of changes, this release is “dominated” by wireless networking and GPU driver updates, however, Torvalds doesn’t think that anything really huge stands out this time. While nothing stands out Torvalds urged people to carry on testing and submitting patches. This update saw improvements to the core system and architecture. There have been improvements to ARM64 KVM that improve stability and correctness of virtualizations on ARM64. There are also improvements to RISC-V KVM and Trust Domain Extensions (TDX) for Intel which expand and secure virtualization capabilities on those architectures. On the graphics front, there are fixes for the amdgpu and amdkfd drivers that fix job handling, engine resets, display corruption, and power management features. The driver used for Qualcomm’s Adreno GPUs has been updated to improve fault handling, display timing, and driver binding. The open-source Nouveau (Nvidia) driver has been updated with fixes for GSP message queue references, potential integer overflows, buffer size adjustments, and a use-after-free bug. Finally, the Intel i915 driver has been updated to address early wedge issues, memory initializations, and build errors. There are also improvements to Wi-Fi devices (ath12k and iwlwifi), sound (ALSA), power management on AMD, and file system improvements (OverlayFS, EROFS, XFS, NFS, SunRPC). Linux 6.16 is due for release at the end of July and will then be picked up by Linux distributions, which will be the first interaction most end users have with the new features in this update. The main benefit of a newer kernel is that Linux will work on newer hardware, so if you’ve had issues with Linux, be sure to try it periodically in case your hardware is now supported.
    • Technically, it should be account-bound after activating it
  • Recent Achievements

    • Week One Done
      urbanmopdubai1 earned a badge
      Week One Done
    • One Month Later
      Jim Dugan earned a badge
      One Month Later
    • First Post
      Johnny Mrkvička earned a badge
      First Post
    • Week One Done
      viraltui earned a badge
      Week One Done
    • One Month Later
      serfegyed earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      645
    2. 2
      Michael Scrip
      226
    3. 3
      ATLien_0
      219
    4. 4
      Steven P.
      150
    5. 5
      Xenon
      146
  • Tell a friend

    Love Neowin? Tell a friend!