尽管在大多数情况下没有必要,但高级控制作者可以选择替代逻辑树。
例
本示例介绍如何创建 StackPanel 子类以重写逻辑树,在本示例中重写逻辑树是为了强制该面板只能具有并且仅仅呈现一个子元素的行为。 这不一定是实际需要的行为,但在这里进行演示是为了举例说明重写元素的正常逻辑树的情况。
public class SingletonPanel : StackPanel
{
//private UIElementCollection _children;
private FrameworkElement _child;
public SingletonPanel()
{
}
public FrameworkElement SingleChild
{
get { return _child; }
set
{
if (value == null)
{
RemoveLogicalChild(_child);
}
else
{
if (_child == null)
{
_child = value;
}
else
{
// raise an exception?
MessageBox.Show("Needs to be a single element");
}
}
}
}
public void SetSingleChild(object child)
{
this.AddLogicalChild(child);
}
public new void AddLogicalChild(object child)
{
_child = (FrameworkElement)child;
if (this.Children.Count == 1)
{
this.RemoveLogicalChild(this.Children[0]);
this.Children.Add((UIElement)child);
}
else
{
this.Children.Add((UIElement)child);
}
}
public new void RemoveLogicalChild(object child)
{
_child = null;
this.Children.Clear();
}
protected override IEnumerator LogicalChildren
{
get
{
// cheat, make a list with one member and return the enumerator
ArrayList _list = new ArrayList();
_list.Add(_child);
return (IEnumerator)_list.GetEnumerator();
}
}
}
有关逻辑树的详细信息,请参阅 WPF中的