我正在使用DrawingContext.DrawLine
函数来绘制线条。但看起来线条会影响 Canvas 上其他线条的位置。所以我需要为所有行添加不同的 z-index 值。有什么方法可以绘制具有不同 z-index 的线,这样它们就不会影响其他线的位置。或者是否有其他方法可用于绘制线条,例如绘制文本,我已将 DrawText
方法替换为 TextBlock
。
下面是我现在使用的示例代码:
DrawingGroup dGroup = new DrawingGroup();
DrawingContext dc = dGroup.Open()
dc.DrawLine(penScaleMarker, new Point((float)newPointX, (float)newPointY), new Point((float)newMinorEndX, (float)newMinorEndY));
最佳答案
为了将动态形状集合添加到 Canvas,您通常会声明一个 ItemsControl,并将 Canvas 作为其 ItemsPanel
。 Canvas 的 ItemsSource
属性将绑定(bind)到以抽象方式表示形状数据的数据项集合。 ItemsControl 的 ItemTemplate
将负责可视化每个单独的项目。
<ItemsControl ItemsSource="{Binding ShapeItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path Data="{Binding Geometry}"
Stroke="{Binding Stroke}"
StrokeThickness="2"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
定义数据项类的 View 模型如下所示。请注意,除了 Geometry
和 Stroke
属性之外,您可能还有其他定义视觉外观的属性。
public class ShapeItem
{
public Geometry Geometry { get; set; }
public Brush Stroke { get; set; }
}
public class ViewModel
{
public ObservableCollection<ShapeItem> ShapeItems { get; }
= new ObservableCollection<ShapeItem>();
}
您可以在主窗口中实例化并初始化它,如下所示:
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel();
vm.ShapeItems.Add(new ShapeItem
{
Geometry = new LineGeometry(new Point(100, 100), new Point(200, 200)),
Stroke = Brushes.Green
});
vm.ShapeItems.Add(new ShapeItem
{
Geometry = new LineGeometry(new Point(200, 200), new Point(100, 300)),
Stroke = Brushes.Red
});
DataContext = vm;
}
您现在可以向 ShapeItem 类添加 ZIndex
属性
public class ShapeItem
{
public Geometry Geometry { get; set; }
public Brush Stroke { get; set; }
public int ZIndex { get; set; }
}
并将以下内容添加到 ItemsControl:
<ItemsControl ItemsSource="{Binding ShapeItems}">
...
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Panel.ZIndex" Value="{Binding ZIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
ShapeItem 类还必须实现 INotifyPropertyChanged
接口(interface),以防其属性在添加到集合后更改其值。
关于c# - 如何在c# wpf应用程序中绘制具有不同z索引的多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40718555/