简体   繁体   English

将Storyboard绑定到从Code Behind添加的元素

[英]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. 嗨,我在WPF中得到了这个故事板,效果很好,但我需要为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. 这是Works,但正如我所提到的,我需要将其更改为从Code Behind运行。 Was thinking about something like this, but I can't get the Binding to work. 正在考虑这样的事情,但我无法让Binding工作。

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. 您可以使用Storyboard.Target属性而不是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: 首先删除XAML的TargetName属性,并为动画添加名称,以便在代码隐藏中引用它:

<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! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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