我試圖寫一個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中的代碼正在拋出異常。
顯然我做的不正確,但文檔沒有提供任何示例,我的搜索似乎表明,要麼沒有人嘗試這個,要麼任何嘗試它的人都不會談論它。有沒有人有建議?