2009-02-02 81 views
0

我試圖寫一個ParentAdapter的實現;我感興趣的是爲我正在編寫的一些WPF控件提供設計時支持,這就是如何管理用於將項目重新映射到不同容器控件的自定義邏輯。我從小開始創建一個StackPanel衍生類,只允許Button元素在設計階段被初始化(是的,我知道面板本身也需要代碼來支持這一點)。我想將是最簡單的ParentAdapter可能是:什麼是簡單的ParentAdapter實現?

using System; 
using System.Windows; 
using System.Windows.Controls; 
using Microsoft.Windows.Design.Interaction; 
using Microsoft.Windows.Design.Model; 

namespace ControlLibrary.Design 
{ 
    internal class SimplePanelParentAdapter : ParentAdapter 
    { 
     public override bool CanParent(ModelItem parent, Type childType) 
     { 
      return (childType == typeof(Button)); 
     } 

     // moves the child item into the target panel; in this case a SimplePanel 
     public override void Parent(ModelItem newParent, ModelItem child) 
     { 
      using (ModelEditingScope undoContext = newParent.BeginEdit()) 
      { 
       // is this correct? 
       //child.Content.SetValue("I'm in a custom panel!"); 
       SimplePanel pnl = newParent.GetCurrentValue() as SimplePanel; 
       pnl.Children.Add(child.GetCurrentValue() as UIElement);     
       undoContext.Complete(); 
      } 

     } 

     public override void RemoveParent(ModelItem currentParent, ModelItem newParent, ModelItem child) 
     { 
      // No special things need to be done, right? 
      child.Content.SetValue("I was in a custom panel."); 
     } 
    } 
} 

當我在設計時有這方面的工作,只要我在我的自定義面板拖動按鈕,NullReferenceException從深VS代碼中拋出。我的代碼沒有拋出異常,因爲我可以通過我的方法一路走下去;調用堆棧指示Microsoft.Windows.Design.Developer.dll中的代碼正在拋出異常。

顯然我做的不正確,但文檔沒有提供任何示例,我的搜索似乎表明,要麼沒有人嘗試這個,要麼任何嘗試它的人都不會談論它。有沒有人有建議?

回答

0

我自己找到了我的問題的答案。該問題是由編輯模型而不是ModelItem包裝引起的。我應該做的(和不工作)是這樣的:

using System; 
using System.Windows.Controls; 
using Microsoft.Windows.Design.Interaction; 
using Microsoft.Windows.Design.Model; 

namespace ControlLibrary.Design 
{ 
    internal class SimplePanelParentAdapter : ParentAdapter 
    { 
     public override bool CanParent(ModelItem parent, Type childType) 
     { 
      return (childType == typeof(Button)); 
     } 

     // moves the child item into the target panel; in this case a SimplePanel 
     public override void Parent(ModelItem newParent, ModelItem child) 
     { 
      using (ModelEditingScope undoContext = newParent.BeginEdit()) 
      { 
       ModelProperty prop = newParent.Properties["Children"]; 
       ModelItemCollection items = (ModelItemCollection)prop.Value; 
       items.Add(child); 

       undoContext.Complete(); 
      } 

     } 

     public override void RemoveParent(ModelItem currentParent, ModelItem newParent, ModelItem child) 
     { 
      using (ModelEditingScope scope = child.BeginEdit()) 
      { 
       ModelProperty prop = currentParent.Properties["Children"]; 
       ((ModelItemCollection)prop.Value).Remove(child); 

       scope.Complete(); 
      } 
     } 
    } 
} 

我很困惑,當我寫的第一個代碼,並不能確定,我應該如何調用Add()方法對兒童財產;它看起來像ModelProperty.Value包裝與ModelItemCollection集合,所以除非你讓你的類使用鈍的接口,這應該工作。

相關問題