2012-05-11 38 views
1

我有一個非常簡單的用戶控件啓動時加載一個陸侃條動畫:的DataContext與EventTriggers與Window.SizeToContent

<UserControl x:Class="WpfApplication2.UserControl1" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <ProgressBar Width="200" Height="10" Maximum="{Binding Delay}" SmallChange="1"> 
     <ProgressBar.Triggers> 
      <EventTrigger RoutedEvent="ProgressBar.Loaded"> 
       <BeginStoryboard> 
        <Storyboard> 
         <DoubleAnimation 
         Storyboard.TargetProperty="Value" To="{Binding Delay}" Duration="00:00:10" /> 
        </Storyboard> 
       </BeginStoryboard> 
      </EventTrigger> 
     </ProgressBar.Triggers> 
    </ProgressBar> 
</UserControl> 

動畫的To價值來自用戶控件的DataContext的:

class ViewModel 
{ 
    public int Delay 
    { 
     get { return 10; } 
    } 
} 

的用戶控件顯示在一個窗口,都放在一起這樣的:

var w = new Window(); 
var vm = new ViewModel(); 
var c = new UserControl1 {DataContext = vm}; 
w.Content = c; 
w.Owner = this; 
w.WindowStartupLocation = WindowStartupLocation.CenterOwner; 
// to make the animation play, I have to remove the following line 
w.SizeToContent = SizeToContent.WidthAndHeight; 
w.ShowDialog(); 

,我也行

w.SizeToContent = SizeToContent.WidthAndHeight;

在我的代碼動畫沒有限制,只要打。

有沒有人對這種非常奇怪的行爲有一個解釋,並可以想出一個解決方案?

最終目標非常簡單。我想要的只是一個進度條,在加載UserControl/Window後的一段時間內(通過viewmodel指定)進行動畫處理。最好僅限XAML。

回答

2

而不是

w.SizeToContent = SizeToContent.WidthAndHeight 

使用的代碼,它的凌亂我同意,但是它的工作原理

w.SourceInitialized += (s, a) => 
      { 

       w.SizeToContent = SizeToContent.WidthAndHeight; 

       w.UpdateLayout(); 
       w.Left = this.Left + (this.ActualWidth/2.0 - w.ActualWidth/2.0); 
       w.Top = this.Top + (this.ActualHeight/2.0 - w.ActualHeight/2.0); 
      }; 

我沒有爲解釋很遺憾。我只知道WPF的工作方式以及Windows在內部如何對待Windows的方式可能會有時會發生衝突。我在設置窗口的左/上/寬/高時遇到同樣的問題,然後直接將其最大化。爲了解決它,我只是延遲它,直到SourceInitialized事件被解僱。我試着對你的代碼也是這樣,它看起來像是一個類似的問題,因爲這有訣竅。

+0

這幾乎可行。當它播放動畫時,會打破WindowStartupLocation.CenterOwner。該窗口現在不再居中了。我沒有在原始問題中添加CenterOwner代碼,因爲我認爲這不重要。我更新了我的問題。 – bitbonk

+0

@bitbonk好的,再試一次。擺脫OwnerCenter並自己動手,不幸的是這是我最好的解決方案。 – dowhilefor

相關問題