在 WPF MVVM 的画布上画线不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23561543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:41:36  来源:igfitidea点击:

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

c#wpfcanvasmvvmcaliburn.micro

提问by mans

I have this xaml:

我有这个 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.

我正在使用 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.

1- 视图上的画布未绑定到 ViewModel 中的 DrawCanvas。

2- The drawing code is not correct.

2-绘图代码不正确。

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.

如何检查我的视图画布是否实际绑定到我的 ViewModel 中的 DrawCanvas?绑定的语法是否正确?我正在使用 Caliburn Micro。

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

如果绑定正确,绘制代码不工作是什么问题?

回答by Flat Eric

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

这就是你可以在 MVVM 中做到的方式(我从这里修改了解决方案: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:



在 ViewModel 中,您需要这样的东西:

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