我創建了一個非常簡單的測試應用程序來嘗試解決由同事描述給我的這個問題。他能夠用C#觸發它,但我相信他需要的解決方案更通用,並且希望嚴格按照XAML進行。問題是:如何觸發UserControl內的Storyboard開始響應包含窗口中控件的事件(父窗口不一定是窗口,它可以是頁面或其他UserControl .. 。爲了簡單起見,我使用了一個窗口)。所以,我最好的例子是你有一個帶按鈕的窗口和你的UserControl的一個實例。您希望Button的Click事件觸發UserControl內的Storyboard開始。僅使用XAML從WPF父窗口控制UserControl的Storyboard
在UserControl本身內部,故事板被MyStoryboard的鍵聲明爲資源。我使用EventTrigger創建了一個Button,以顯示我可以通過引用Binding表達式來觸發Storyboard。這裏是我的用戶完整的XAML:
<UserControl x:Class="UserControlStoryboard.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<Storyboard x:Key="MyStoryboard">
<ColorAnimation Storyboard.TargetName="grid" Storyboard.TargetProperty="(Grid.Background).Color" From="CadetBlue" To="White" Duration="0:0:2" />
</Storyboard>
</UserControl.Resources>
<Grid Background="CadetBlue" x:Name="grid">
<Button Content="Press Me" Height="50">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<BeginStoryboard.Storyboard>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type UserControl}}" Path="Resources[MyStoryboard]" />
</BeginStoryboard.Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
我希望,因爲我能講一個故事板與綁定表達式引用它,我應該能夠做到精確的開始包含此UserControl的Window作爲子元素的相同事物。但我似乎無法弄清楚如何在父窗口中獲取對Storyboard的引用。這僅僅是不可能在XAML中完成的嗎?
我的測試項目中的父窗口只有一個按鈕和此UserControl的一個實例。如果甚至可能,哪個元素可以讓我添加EventTrigger,其中事件的來源是Button,觸發器操作告訴UserControl的Storyboard開始?
謝謝。
上我有一個非常類似的情況在UC財產,沒有你有沒有找到這個決議? – Nate 2011-02-23 21:06:30
不幸的是,沒有。兩年前問這個問題。從那以後,我用模板綁定做了一些非常有趣的事情,以便在父控件和子控件之間來回傳遞。現在有了我的經驗,我確實更喜歡更直接的C#方法。我看到xaml,綁定,視圖模型等更多花哨的技巧讓我越來越畏懼...可以做出巨大的調試噩夢。 – Rich 2011-02-24 00:10:39