簡體   English   中英

將Storyboard綁定到從Code Behind添加的元素

[英]Binding Storyboard to element added from Code Behind

嗨,我在WPF中得到了這個故事板,效果很好,但我需要為Code Behind加載我的用戶控件。 (其中一些需要一些時間來加載,所以我需要向用戶提供有關加載進度的信息)

無論如何,這是我現在的代碼。

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

我將它們添加到我的代碼中

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

這是Works,但正如我所提到的,我需要將其更改為從Code Behind運行。 正在考慮這樣的事情,但我無法讓Binding工作。

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

引發和錯誤

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

您可以使用Storyboard.Target屬性而不是Storyboard.TargetName。 首先刪除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>

然后在代碼隱藏中,在創建對象后,更新動畫:

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

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM