gulbaek
gulbaek

Reputation: 2551

Binding Storyboard to element added from Code Behind

Hi I got this Storyboard in WPF, that works great, but I need to load my user controls for Code Behind. (Some of them take some time to load, so I need to give the user info about the loading progress)

Anyway, this is my code right now.

<ObjectAnimationUsingKeyFrames BeginTime="00:00:00"
    Storyboard.TargetName="businessCard"
       Storyboard.TargetProperty="(UIElement.Visibility)">
          <DiscreteObjectKeyFrame KeyTime="00:00:0.01">
             <DiscreteObjectKeyFrame.Value>
                 <Visibility>Visible</Visibility>
             </DiscreteObjectKeyFrame.Value>
          </DiscreteObjectKeyFrame>
 </ObjectAnimationUsingKeyFrames>

And I add them to my code with

<Grid Name="MyGrid">
    <local:BusinessCard x:Name="businessCard"/>
    <local:MailMessage x:Name="mailMessageCard"
    DataContext="{Binding Path=SelectedItem, ElementName=foldersTreeView}" />
</Grid>

This Works, but as I mentioned I need to change it to run from Code Behind. Was thinking about something like this, but I can't get the Binding to work.

var businessCard = new BusinessCard() {Name = "businessCard"};
MyGrid.Children.Add(businessCard);

Throws and Error

'businessCard' name cannot be found in the name scope of 'System.Windows.Controls.Grid'.

Upvotes: 0

Views: 1359

Answers (1)

alf
alf

Reputation: 18550

You can use the Storyboard.Target property instead of Storyboard.TargetName. First remove the TargetName property of your XAML, and add a name to your animation, so you can reference it in code-behind:

<ObjectAnimationUsingKeyFrames x:Name="MyObjectAnimation" BeginTime="00:00:00"
   Storyboard.TargetProperty="(UIElement.Visibility)">
      <DiscreteObjectKeyFrame KeyTime="00:00:0.01">
         <DiscreteObjectKeyFrame.Value>
             <Visibility>Visible</Visibility>
         </DiscreteObjectKeyFrame.Value>
      </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>

Then in your code-behind, after you create the object, update the animation:

var businessCard = new BusinessCard() {Name = "businessCard"};
MyGrid.Children.Add(businessCard);
MyObjectAnimation.SetValue(Storyboard.TargetProperty, businessCard)

Hope it helps!

Upvotes: 2

Related Questions