Wpf 简单的ParentAdapter实现是什么样子的?
我正在尝试编写ParentAdapter实现;我感兴趣的是为我正在编写的一些WPF控件提供设计时支持,这就是如何管理自定义逻辑,以便将项重新分配到不同的容器控件。我从小开始就有创建StackPanel派生类的想法,该类只允许按钮元素在设计时作为父元素是的,我知道面板本身也需要代码来支持这一点。我从ParentAdapter最简单的功能开始:Wpf 简单的ParentAdapter实现是什么样子的?,wpf,design-time,cider,Wpf,Design Time,Cider,我正在尝试编写ParentAdapter实现;我感兴趣的是为我正在编写的一些WPF控件提供设计时支持,这就是如何管理自定义逻辑,以便将项重新分配到不同的容器控件。我从小开始就有创建StackPanel派生类的想法,该类只允许按钮元素在设计时作为父元素是的,我知道面板本身也需要代码来支持这一点。我从ParentAdapter最简单的功能开始: using System; using System.Windows; using System.Windows.Controls; using Micro
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.");
}
}
}
当我在设计时处理这个问题时,只要我在自定义面板上拖动一个按钮,就会从VS代码的深处抛出一个NullReferenceException。我的代码没有抛出异常,因为我可以一步一步地遍历我的方法;调用堆栈表示Microsoft.Windows.Design.Developer.dll中的代码正在引发异常
很明显,我做了一些不正确的事情,但文档中没有提供任何示例,我的搜索结果似乎表明,要么没有人在尝试,要么尝试的人没有谈论它。有人有什么建议吗?我自己找到了问题的答案。该问题是由编辑模型而不是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();
}
}
}
}
当我编写第一个代码时,我感到困惑,不确定如何调用Children属性上的Add;它看起来像ModelProperty.Value用ModelItemCollection包装集合,所以除非您特意让类使用钝接口,否则这应该可以工作