c# - 在 WPF MVVM 的 Canvas 上画线不起作用

标签 c# wpf canvas mvvm caliburn.micro

我有这个 xaml:

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

在模型中我有:
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);
}

我正在使用 Caliburn Micro。

它不会在输出上绘制任何线。

这个问题可能有两个原因:

1- View 上的 Canvas 未绑定(bind)到 ViewModel 中的 DrawCanvas。

2- 绘图代码不正确。

如何检查我的 View Canvas 是否实际绑定(bind)到我的 ViewModel 中的 DrawCanvas?绑定(bind)的语法是否正确?我正在使用 Caliburn Micro。

如果绑定(bind)正确,绘制代码不起作用的问题是什么?

最佳答案

这就是您可以在 MVVM 中执行此操作的方式(我从这里修改了解决方案:https://stackoverflow.com/a/1030191/3047078):

在 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>

在 ViewModel 中,你需要这样的东西:
public ObservableCollection<MyLine> Lines {get;set;}

在模型中:
public class MyLine
{
  public int X1 {get;set;}
  public int Y1 {get;set;}
  public int X2 {get;set;}
  public int Y2 {get;set;}
}

关于c# - 在 WPF MVVM 的 Canvas 上画线不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561543/

相关文章:

c# - MSMQ 的主要优势

c# - Excel 日期列未正确读取

c# - 从字符串中获取第一个非重复(不同)字符的逻辑

javascript从 Canvas 中删除具有唯一属性的多个对象

javascript - 找到两点之间的中点

c# - 我可以在自定义 WPF Canvas 控件中绘制点网格吗?

c# - 如何确定 Exchange 邮件项目是否为自动回复邮件?

c# - cefSharp ChromiumWebBrowser 大小到页面内容

c# - 对于WPF,免费烛台示例?

c# - 为什么单击树抛出 'System.Windows.Documents.Run' 不是 Visual 或 Visual3D 的 InvalidOperationException?