Hi,
you can use Interactivity.dll (from Nuget) to get reference of Canvas in ViewModel like this:
<Window x:Class="WpfApp1.Window78"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp78"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
Title="Canvas with PolyLine" Height="450" Width="800">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Canvas Grid.Row="0" Background="White">
<i:Interaction.Behaviors>
<local:CanvasBehavior/>
</i:Interaction.Behaviors>
...
public class ViewModel
{
public ViewModel()
{
public Canvas CanvasView { get; set; }
...
if (CanvasView.Children.Count == 0) // first call, create polyline and add to Canvas
{
pline.Stroke = new SolidColorBrush(Color.FromRgb(60, 125, 200));
pline.StrokeThickness = 1;
pline.Points = pointCollection;
CanvasView.Children.Add(pline);
}
...
/// <summary>
/// Behavior to get Canvas in ViewModel (MVVM)
/// </summary>
public class CanvasBehavior : Behavior<Canvas>
{
protected override void OnAttached() =>
AssociatedObject.Loaded += AssociatedObject_Loaded;
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e) =>
((ViewModel)(AssociatedObject.DataContext)).CanvasView = AssociatedObject;
}