HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Lots of Storyboards in XAML, huge file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filexamlhugelotsstoryboards

Problem

After spending a few ages writing out every combination of triggers, bindings and storyboards, I finally managed to get my program working. First time working with WPF, so I made a big mess. Now it's time to put on my refactoring hat and make the code neat and proper again!

That is, if I knew how. Could anyone experienced with WPF or XAML files help me out here and explain how to unmess this code? Suggesting a change of design is fine too, though like I said, this is the only way that I managed to actually get it working.

What the code is supposed to do, is dynamically be able to change sprite animations (by binding a .gif source to an Image), and dynamically "move around" the sprite on a preset animation, different animations depending on what happens in the rest of the code. Like, up and down, or in a circle, or to the corner of the screen and back. Etcetera.

I only copied three storyboards with small changes each per sprite in here for brevity, I suppose you can see what happens when I extend them even further..

```










































Solution

Your markup is inlining the styles, which has the effect of producing extremely redundant markup - as you've noticed.

You can define the resources of a window in its Resources property - step one would be to extract your inline styles into the Window tag:


    
      ...
    
    
      ...
    


Then, you can refer to these styles with a StaticResource markup extension:


    ...


Depending on exactly what the "small value changes" are, you'll want to create a new Style, or put a BasedOn attribute to specify a Style to "derive" from another. An individual element can always override any value determined by its Style.

Once you've extracted the styles into the window's resources, you might want to move them to a ResourceDictionary so you can reuse the same styles in other windows, without having to redefine them over again.

Code Snippets

<Window.Resources>
    <Style x:Key="MyStyle1" TargetType="{x:Type Image}">
      ...
    </Style>
    <Style x:Key="MyStyle2" TargetType="{x:Type Image}">
      ...
    </Style>
</Window.Resources>
<Image Style="{StaticResource MyStyle1}">
    ...
</Image>

Context

StackExchange Code Review Q#43821, answer score: 6

Revisions (0)

No revisions yet.