Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 是否可以创建一个控件,并在每次需要时生成它?_Wpf_Dynamic_Components - Fatal编程技术网

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

Wpf 是否可以创建一个控件,并在每次需要时生成它?,wpf,dynamic,components,Wpf,Dynamic,Components,例如,假设您有一个stackpanel,您希望以编程方式向其添加按钮 按钮生成和添加到stackpanel的代码如下: Button button = new Button(); button.Content = "Button"; button.HorizontalAlignment = HorizontalAlignment.Left; button.Name = "Button" + i stackPanel1.Children.Add(button); 我的问题是-是否可以生成一次按钮

例如,假设您有一个stackpanel,您希望以编程方式向其添加按钮

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

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

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

在WPF中,每个UIElement在任何给定时间都只能是一个控件的逻辑子级,请参阅,所以不,你不能使用同一个按钮,以后再将它添加到另一个控件,除非你确定你已经摆脱了stackpanel

但是,你可以做回收。看见特别是如果您愿意覆盖stackpanel的
测量覆盖
排列覆盖

我实际上编写了这样一个回收器,因为我有很多控件的网格,我想实现某种虚拟化网格。以下是我们班的主要方法:

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
    }
}