我正在从Silverlight应用程序中打印一组标签。从数据库中读取构成数据的数据,并且动态创建UI元素并将其添加到Canvas
以进行布局。标签以网格形式排列在页面上,行数和列数由正在使用的纸张库存确定。
除了添加一行“击出”元素(例如商品在售时的原始价格)之外,一切都运行正常:
这是生成行的代码:
var line = new Line { StrokeThickness = 2, Stroke = new SolidColorBrush(Colors.Black) };
line.X1 = 0;
line.SetBinding(Line.Y1Property, new Binding { ElementName = element.Name, Path = new PropertyPath("ActualHeight") });
line.Y2 = 0;
line.SetBinding(Line.X2Property, new Binding { ElementName = element.Name, Path = new PropertyPath("ActualWidth") });
// Insert the element straight after the element it's bound to
canvas.Children.Insert(canvas.Children.IndexOf(element) + 1, line);
line.SetValue(Canvas.TopProperty, element.GetValue(Canvas.TopProperty));
line.SetValue(Canvas.LeftProperty, element.GetValue(Canvas.LeftProperty));
// and make sure it's Z index is always higher
line.SetValue(Canvas.ZIndexProperty, (int)element.GetValue(Canvas.ZIndexProperty) + 1);
canvas
是用于显示标签element
是要插入的元素(在这种情况下是原始价格)。ActualHeight
和ActualWidth
都相同。我错过了什么?
答案 0 :(得分:1)
似乎是绑定有问题。无论我做什么,一旦我添加回来的线条消失了 - 在某些情况下甚至从第一页开始。
最后,唯一有效的方法是将代码更改为:
element.Measure(new Size(canvas.Width, canvas.Height));
var line = new Line { StrokeThickness = 2, Stroke = new SolidColorBrush(Colors.Black) };
line.X1 = 0.0;
line.Y1 = element.ActualHeight;
line.Y2 = 0.0;
line.X2 = element.ActualWidth;
// Insert the element straight after the element it's bound to
canvas.Children.Insert(canvas.Children.IndexOf(element) + 1, line);
line.SetValue(Canvas.TopProperty, element.GetValue(Canvas.TopProperty));
line.SetValue(Canvas.LeftProperty, element.GetValue(Canvas.LeftProperty));
// and make sure it's Z index is always higher
line.SetValue(Canvas.ZIndexProperty, (int)element.GetValue(Canvas.ZIndexProperty) + 1);
line.Height = element.ActualHeight;
line.Width = element.ActualWidth;
所以我“测量”文本元素以确保它的高度和宽度更新,然后直接设置Y1
,X2
,Height
和Width
属性文本元素的ActualHeight
和ActualWidth
。这会将线条绘制在正确的位置和正确的尺寸。