![](/img/trans.png)
[英]How to use WPF ContentControl 's content with DataTemplate
[英]WPF - How to get ActualHeight of ContentControl's content?
這是一些代碼:
<components:AnimatedContentControl x:Name="MainContent" Content="{Binding}">
<components:AnimatedContentControl.Triggers>
<EventTrigger RoutedEvent="components:AnimatedContentControl.ContentChanged">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="MainContent"
Storyboard.TargetProperty="Height"
Duration="0:0:0.25"
From="0"
To="{Binding ElementName=MainContent, Path=ActualHeight}" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</components:AnimatedContentControl.Triggers>
</components:AnimatedContentControl>
AnimatedContentControl
是我根據ContentControl創建的類,該類內部具有ContentChanged
路由事件(由於某種原因, ContentControl
默認情況下沒有ContentChanged
事件)。
這段代碼的目標是將應用程序的DataContext
指向的任何內容加載到此ContentControl
,並在更改數據上下文時顯示一個簡單的動畫,該動畫包括從零到新內容大小的幻燈片(理想情況下) ,它將從舊內容的高度滑動到新內容的高度,但首先要執行第一步)。 對於這樣一個簡單的想法,這已經很難開發了。
我已經知道我的問題是:當此事件觸發時, AnimatedContentControl
的Content
屬性已更新,但是由於某種原因, AnimatedContentControl
的ActualSize
尚未(實際上,想到它,我可能會使用ActualSize
屬性為DoubleAnimation
的From
屬性的屬性-我稍后再嘗試)。
所以我的問題是: DoubleAnimation
可以綁定哪些東西,它是AnimatedContentControl
內容的實際大小? 如果是這樣,那是什么? 如果沒有,有哪些解決方法?
鮑里斯是對的-我的代碼現在看起來像這樣:
<components:AnimateableContentControl x:Name="MainContent" Content="{Binding}">
<components:AnimateableContentControl.Triggers>
<EventTrigger RoutedEvent="components:AnimateableContentControl.ContentChanged">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
x:Name="TransitionAnimation"
Storyboard.TargetName="MainContent"
Storyboard.TargetProperty="Height"
Duration="0:0:0.25"
From="0"
To="0" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</components:AnimateableContentControl.Triggers>
</components:AnimateableContentControl>
...以及我更改DataContext
的位置(導致動畫)的地方,我有:
DataTemplate template = Resources[new DataTemplateKey(m_currentViewModel.GetType())] as DataTemplate;
if (template == null)
{
DataContext = m_currentViewModel;
return;
}
FrameworkElement element = template.LoadContent() as FrameworkElement;
if (element == null)
{
DataContext = m_currentViewModel;
return;
}
element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
TransitionAnimation.To = element.DesiredSize.Height;
DataContext = m_currentViewModel;
奇跡般有效! 謝謝鮑里斯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.