将UserControl动态添加到Canvas,而无需不必要地调用OnRender

时间:2013-12-10 11:06:12

标签: c# wpf

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
}

1 个答案:

答案 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;
}