简体   繁体   中英

What is the correct way to define classes in Xaml?

'ma newbie and I'm playing around with Windows Presentation Foundation using framework 3.5 , and i just got started with story boards and animations. I tried creating instances of Canvas and animating the canvas using instances of Story Board + animations, and it was fun. Now I wanna come up with some organized way with which I can define many animations easily and to use them (defining the object instances inside code is too tedious).

I heard of using XAML to do that, and I've seen some examples in CodeProject.com, but they all seem to be defining UserControls with the storyboards inside them. That seems too hard for me, what I wanna do is just define the storyboard tags and the animation tags inside the storyboard tags, as a Class, is it possible to do it this way? What I mean is, is it possible to define a class (not a User Control) in XAML, and then call its variables like "StoryBoard1" or "StoryBoard2" whenever I wanna use that particular animation? How should I go about implementing it?

You can define Storyboards etc in the Window.Resources if you want reusable animations.

These are known as Resources not Classes

Example:

<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="233" Width="405" Name="UI" >
    <Window.Resources>
        <Storyboard x:Key="MyAnimation" Storyboard.TargetProperty="Opacity">
            <DoubleAnimation From="0" To="1" Duration="0:0:5" />
        </Storyboard>
    </Window.Resources>

    <Grid>
        <Button Content="Animate" Name="button1" Opacity="0" >
            <Button.Style>
                <Style TargetType="{x:Type Button}" >
                    <Style.Triggers>
                        <Trigger Property="IsPressed" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource MyAnimation}" />
                            </Trigger.EnterActions>
                        </Trigger>
                    </Style.Triggers>
                </Style>
             </Button.Style>
        </Button>
    </Grid>
</Window>

To access these resources from code behind you can use FindResource

namespace WpfApplication8
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var storyboard = (Storyboard)FindResource("MyAnimation");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM