是否可以创建一次控件并在每次需要时生成它?

时间:2017-01-30 00:30:51

标签: wpf dynamic components

比如说你有一个堆栈面板,你想以编程方式添加按钮。

生成按钮和添加到stackpanel的代码是:

Button button = new Button();
button.Content = "Button";
button.HorizontalAlignment = HorizontalAlignment.Left;
button.Name = "Button" + i
stackPanel1.Children.Add(button);

我的问题是 - 是否可以生成按钮一次并将其作为某种模板,可以在需要时添加到堆栈面板而无需再次通过生成代码?

1 个答案:

答案 0 :(得分:0)

在WPF中,每个UIElement在任何给定时间都只能是一个控件的逻辑子节点,请参阅WPF Error: Specified element is already the logical child of another element. Disconnect it first,所以不能在以后使用相同的按钮并将其添加到另一个控件,除非你'确定你已经摆脱了那个stackpanel

但是,你可以做回收。见Optimizing Performance: Controls。特别是如果您愿意覆盖堆栈面板的MeasureOverrideArrangeOverride

我实际上已经编写了这样的回收器,因为我有许多控件的网格,我想实现某种虚拟化网格。这些是我班级的主要方法:

internal class Recycler
{
    private UIElementCollection _children;

    public Recycler(UIElementCollection children)
    {
         _children = children;
         //You need this because you're not going to remove any
         //UIElement from your control without calling this class
    }

    public void Recycle(UIElement uie)
    {
        //Keep this element for recycling, remove it from Children
    }

    public UIElement GiveMeAnElement(Type type)
    {
        //Return one of the elements you kept of this type, or
        //if none remain create one using the default constructor
    }
}