2013-04-25 49 views
2

我有一個控件,我添加了一個自定義行爲。C#如何確保一個WPF控件的全部負載

行爲有兩個DependencyProperties:

public SomeObject Player { 
    get { return (e)GetValue(PlayerProperty); } 
    set { SetValue(PlayerProperty, value); } 
} 

// Using a DependencyProperty as the backing store for Player. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty PlayerProperty = 
    DependencyProperty.Register("Player", typeof(IVideoPlayerDTO), typeof(PlayerStreamBehavior), new UIPropertyMetadata(null)); 

public IntPtr Handle { 
    get { return (IntPtr)GetValue(HandleProperty); } 
    set { SetValue(HandleProperty, value); } 
} 

// Using a DependencyProperty as the backing store for Handle. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty HandleProperty = 
     DependencyProperty.Register("Handle", typeof(IntPtr), typeof(PlayerStreamBehavior), new UIPropertyMetadata(IntPtr.Zero, OnHandleChanged)); 

每一個綁定到WPF中某些對象。 問題是,Handle屬性的OnHandleChanged在具有行爲的控件完全加載之前被激活,這會在嘗試向控件添加HwndHost時引發異常。 我如何確保在我嘗試添加HwndHost之前控件已完全加載? P.S:儘量選用OnAttached(),然而這並沒有工作...

+0

如何'OnHandleChanged'實施? * [...]拋出一個異常[*] *非常具體的錯誤描述。 - 那麼它說什麼? – DHN 2013-04-25 15:15:03

+0

我得到的錯誤是: 「BuildWindowCore未能返回託管的子窗口句柄。」 當我嘗試構建HandleRef時: HandleRef refhandle = new HandleRef(this,Player.Handle); 一切都順利,但是當我嘗試將其返回到它失敗的方法。 – VitalyP 2013-04-28 05:52:14

回答

1

試試這個:

public MyControl() 
{ 
    this.Loaded += MyControl_Loaded; 
} 

private void MyControl_Loaded(object sender, RoutedEventArgs e) 
{ 
    // Control is full loaded 
} 
+0

當UserControl完全加載時觸發加載的事件 – 2013-04-25 15:15:53

+0

我無法使用Loaded事件,因爲我在行爲時需要知道AssociatedObject是否已加載,以及何時寫入: AssociatedObject.Loaded + = AssociatedObject_Loaded ;在AssociatedObject尚未創建的行爲的ctor中,它是空的。 – VitalyP 2013-04-28 07:47:51