简体   繁体   中英

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'.

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!

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