Drawing line on a canvas in WPF MVVM doesn't work

柔情痞子 提交于 2019-12-02 15:49:43

问题


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?


回答1:


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;}
}


来源:https://stackoverflow.com/questions/23561543/drawing-line-on-a-canvas-in-wpf-mvvm-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!