将UserControl
动态添加到Canvas
的正确方法是什么?我需要添加很多项目,并且我希望仅在需要时调用OnRender
(当UserControl
在屏幕上时)。
现在,在OnRender
创建/添加UserControl
时会调用Canvas
,我不喜欢这样,因为它使用了额外的资源。
// Main Window Code
int y = 0;
foreach(MyData d in data)
{
// allocate control
MyControl ctrl = new MyControl();
// initialize properties
ctrl.Name = d.Name;
ctrl.Phone = d.Phone;
// add control to canvas
canvas.Children.Add(ctrl);
// setup position
Canvas.SetLeft(ctrl, 0);
Canvas.SetTop(ctrl, y);
y += Height;
}
// UserControl (MyControl) code
protected override void OnRender(DrawingContext drawingContext)
{
// custom draw code for Name & Phone
}
答案 0 :(得分:0)
添加一个简单的布尔标志:
//Main Window Code
bool canRender = false;
int y=0;
foreach(MyData d in data)
{
//allocate control
MyControl ctrl=new MyControl();
//initialize properties
ctrl.Name=d.Name;
ctrl.Phone=d.Phone;
//add control to canvas
canvas.Children.Add(ctrl);
//setup position
Canvas.SetLeft(ctrl, 0);
Canvas.SetTop(ctrl, y);
y+=Height;
}
canRender = true;
InvalidateVisual();
//UserControl code
protected override void OnRender(DrawingContext drawingContext)
{
if(!canRender)
return;
}