[英]How do I start a Storyboard in a Data Template in a Content Control in a User Control from codebehind?
唷。
我是認真的。 我將拼寫如下......
故事板有一個鍵“myStoryboard”。 它保存在一個帶有鍵“myDataTemplate”的DataTemplate中。
此數據模板在ContentControl中使用,此標記名稱為“myContentControl”:
<ContentControl Name="myContentControl"
ContentTemplate="{DynamicResource myDataTemplate}"/>
內容控件在我的UserControl中使用。 在UserControl代碼隱藏中,我做了一個鍵盤手勢,應該啟動“myStoryBoard”,但我沒有這樣的運氣。
private void StartSB(object sender, ExecutedRoutedEventArgs e)
{
Storyboard sb = (Storyboard) this.TryFindResource("myStoryboard");
sb.Begin(this);
}
sb在這里總是為空。 我怎樣才能獲得故事板?
更新:
所以玩TryFindResource()我已經設法進入myDataTemplate
private void StartSB(object sender, ExecutedRoutedEventArgs e)
{
object sb = this.myContentControl.TryFindResource("myDataTemplate");
}
在Locals查看器中,我可以看到sb是myDataTemplate。 我可以在樹中看到sb.base.Resources.Keys,這是一個“myStoryboard”所在的資源數組。 哦,這么近!
UPDATE2:
這里有更多代碼。 我現在意識到,用文字解釋這可能太過分了。
<UserControl >
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources\myUCResources.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<ContentControl Name="myContentControl"
ContentTemplate="{DynamicResource myDataTemplate}"
Content="{Binding}" />
...
</UserControl>
現在這個用戶控件的代碼隱藏
namespace myclass
{
public partial class myUserControl: UserControl, System.ComponentModel.INotifyPropertyChanged
{
...
public myUserControl()
{
InitializeComponent();
<!--setup keybinding-->
}
public void KeyBindExecuted(object sender, ExecutedRoutedEventArgs e)
{
Object sb = this.myContentControl.TryFindResource("myDataTemplate");
//sb returns the DataTemplate
}
}
}
最后是包含UI內容和我最終想要觸發的動畫的資源字典。 (myUCResources.xaml)
<ResourceDictionary>
<DataTemplate x:Key="myDataTemplate" >
<Grid>
<!-- elements like buttons -->
</Grid>
<DataTemplate.Resources>
<Storyboard x:Key="myStoryBoard">
<DoubleAnimation>
<!-- animation stuff-->
</DoubleAnimation>
</Storyboard>
</DataTemplate.Resources>
<DataTemplate.Triggers>
<EventTrigger SourceName="aButton" RoutedEvent="Button.Click">
<BeginStoryboard Storyboard="{StaticResource myStoryBoard}" />
</EventTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ResourceDictionary>
更新3:
確定不同的方法。 我可以從代碼隱藏中使用DataTemplate中的EventTrigger來啟動動畫嗎?
啊哈哈!
所以我找到了解決這個問題的迂回方式。 我的第三次更新,我接受了發射事件的想法似乎更有成效。 所有都可以在這里找到。
http://www.codeproject.com/script/Forums/View.aspx?fid=1004114&msg=2827455
簡而言之,我使用FindResource獲取DataTemplate,然后使用DataTemplate中的按鈕的FindName來正常觸發動畫。 然后我按下了那個按鈕的按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.