Question

I have this xaml:

<Canvas cal:View.Context="DrawCanvas">
    <!--<Line  X1="1" Y1="1" X2="400" Y2="400" Stroke="Black" StrokeThickness="20" IsHitTestVisible="False"/>-->
</Canvas>

and in model I have:

public Canvas DrawCanvas { get; set; }
public ImageSourceViewModel()
{
    this.PropertyChanged += this.ImageSourceViewModel_PropertyChanged;
    this.Scale = 1;
    this.TranslateX = 0;
    this.TranslateY = 0;
    DrawCanvas=new Canvas();
    var line = new Line();
    line.X1= 1;
    line.Y1 = 1;
    line.X2 = 100;
    line.Y2 = 10;
    line.Stroke=new SolidColorBrush(Colors.Green);
    line.StrokeThickness = 2;
    line.Visibility=Visibility.Visible;
    DrawCanvas.Children.Add(line);
}

I'm using Caliburn Micro.

It doesn't draw any line on output.

There could be two reason for this problem:

1- The canvas on view is not bind to DrawCanvas in ViewModel.

2- The drawing code is not correct.

How can I check that the my view canvas is actually bind to DrawCanvas in my ViewModel? Is the syntax for binding correct? I am using Caliburn Micro.

If the binding is correct, what the problem with drawing code that it is not working?

Was it helpful?

Solution

That is the way you can do it in MVVM (I modified the solution from here: https://stackoverflow.com/a/1030191/3047078):

In the view:

<ItemsControl ItemsSource="{Binding Path=Lines}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <Canvas Background="White" Width="500" Height="500"  />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Line X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}" Y2="{Binding Y2}" Stroke="Black" StrokeThickness="3"></Line>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>



In the ViewModel, you need something like this:

public ObservableCollection<MyLine> Lines {get;set;}


In the Model:

public class MyLine
{
  public int X1 {get;set;}
  public int Y1 {get;set;}
  public int X2 {get;set;}
  public int Y2 {get;set;}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top