我的应用程序在画布上显示了许多线条和多边形/路径。我的 ViewModel 包含一系列ObservableCollections
代表要绘制的不同项目。
我遇到的问题是应用程序的缩放和平移速度非常慢。缩放和平移都使用IvalueConverter
和从世界坐标系转换到画布坐标系来处理。
为此,我必须对NotifyPropertyChange
屏幕上可见的所有对象强制使用最新的平移和缩放值重新绘制它们。它适用于几百行,但对于数千行它非常慢。而且,如果您缩小以使所有对象都可见,因此受到NotifyPropertyChange
超过 10,000 行的影响几乎无法使用。
我没有以任何方式使用多边形内置功能,因为所有处理、选择移动等都在视图模型中处理。因此,我想尝试使用,DrawingVisual
而不是Shapes
据我了解它们的开销要低得多,但我找不到任何好的 MVVM 示例来说明如何使用它们。我看到的示例表明它们是在代码隐藏中构建的,这不是我认为我应该使用它们的方式。
示例如下:
//new DrawingVisual
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
Rect rect = new Rect(new System.Windows.Point(160, 100), new System.Windows.Size(320, 80));
drawingContext.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);
drawingContext.Close();
//creating a Host as follows:
public MyVisualHost()
{
_children = new VisualCollection(this);
_children.Add(CreateDrawingVisualRectangle());
_children.Add(CreateDrawingVisualText());
_children.Add(CreateDrawingVisualEllipses());
this.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(MyVisualHost_MouseLeftButtonUp);
}
除非有 WPF 方法可以使用绑定到我的 observable 集合,否则DrawingVisual
我需要在我的模型中创建和删除绘图对象。每次更新模型时,它都必须更新我的drawingVisual
. 但后来我在模型中创建视图项目,这不是正确的方法。谁能建议我应该如何实施 DrawingVisual
而不是Shapes
在我的 MVVM 应用程序中?
这是我当前使用的代码的摘录Shapes
XAML
<ItemsControl x:Name="Catchments">
<ItemsControl.Resources>
<CollectionViewSource x:Key="CatchmentPolygons" Source="{Binding Path=NetworkMain.Catchments}"></CollectionViewSource>
<DataTemplate DataType="{x:Type cad:Catchment}">
<Polygon
Stroke="{Binding IsSelected, Mode=OneWay, Converter={StaticResource ObjectColour}, ConverterParameter=Catchment}"
StrokeThickness="1"
Visibility="{Binding Visible, Mode=OneWay, TargetNullValue='Hidden'}"
Points="{Binding Points, Mode=OneWay, Converter={StaticResource CollectionPointConverter}}">
<Polygon.Fill>
<SolidColorBrush
Color="{Binding IsSelected, Mode=OneWay, Converter={StaticResource ObjectColour}, ConverterParameter=Catchment}"
Opacity=".25"
>
</SolidColorBrush>
</Polygon.Fill>
</Polygon>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource CatchmentPolygons}}"></CollectionContainer>
</CompositeCollection>
</ItemsControl.ItemsSource>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas
ClipToBounds="true">
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
我的可观察集合在我的ViewModel
:
public ObservableCollection<Conduit> Conduits { get; set; } = new();
public ObservableCollection<Node> Nodes { get; set; } = new();
public ObservableCollection<Catchment> Catchments { get; set; } = new();
编辑
带有放大和缩小视图的画布屏幕截图:
缩小:
图像已经缩放了一点,但实际上,当您放大和缩小时,线条粗细、节点大小和箭头保持不变。只有节点的投影坐标发生变化。
放大: