c# - 如何在c# wpf应用程序中绘制具有不同z索引的多条线

标签 c# wpf canvas drawingcontext

我正在使用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 模型如下所示。请注意,除了 GeometryStroke 属性之外,您可能还有其他定义视觉外观的属性。

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/

相关文章:

c# - 将 MBF 单精度和 double 转换为 IEEE

c# - 修改 Dll 中的硬编码路径

c# - Wpf 窗口 Showdialog 没有获得焦点

c# - 将异步/等待与 Dispatcher.BeginInvoke() 结合使用

c# - 值类型相对于引用类型的好处?

c# - 如何在不重新编译的情况下将键/值添加到语言 (*.resx) 文件?

c# - Google API (Gmail) 因先决条件失败 400 而失败

javascript - 如何检测点击后鼠标按钮是否被按住一定时间

java - Android:更新窗口内 View 的线程

javascript - 在 Canvas 上绘制之前向图像添加滤镜