1

我正在尝试将 a 链接Polyline到Avalonia MVVM 应用程序中的 a ObservableCollectionof Points,并且我能够让它很好地显示点的初始集合,但是当集合更新时,折线不会显示任何更改。

首先,我尝试使用ReactiveUI的 RaisePropertyChanged 函数,当我有一个文本块或其他可以显示文本的控件时,它可以正常工作,但它实际上并没有更新折线。所以接下来我尝试了像这样实现 INotifyPropertyChanged 的​​ WPF 方法:

public class PCollection : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    public ObservableCollection<Point> Points { get; set; }

    public PCollection()
    {
        Points = new(Database.GetPoints());
    }

    public void NotifyPropertyChanged(string info)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
    }
}

(从绑定到 ObservableList<Point> 的折线不刷新
Database.GetPoints()返回一个IEnumerable<Point>
并通过调用 PCollection 实例的 NotifyPropertyChanged 函数来通知更改,但在页面最初加载后,这同样不会影响折线。

我发现的其他结果涉及从代码中访问和更新绑定本身,而这对于 MVVM 是不可能的。

我也遇到了这个与 Avalonia 非常相关的问题线程,但我不知道如何利用那里发布的“简单修复”,或者即使不编辑 Avalonia 自己的代码也可以。

相关代码片段: 我的部分视图包含折线和一个按钮,该按钮在画布中创建一个随机点CanvasView.axaml

<Grid>
    <Canvas Grid.Row="1"
          Grid.Column="1"
          Width="250"
          Height="250"
          Name="ArtCanvas">
    <Canvas.Background>
      <SolidColorBrush Color="beige"/>
    </Canvas.Background>
    <Polyline Name="jef"
              Points="{Binding Points}"
              Stroke="black"/>
    </Canvas>
  
  <Button Grid.Row="2"
          Grid.Column="1"
          Content="boop"
          Command="{Binding DrawLine}"/>
</Grid>

视图模型的一部分CanvasViewModel.cs

public class CanvasViewModel : ViewModelBase
{
    public ObservableCollection<Point> Points { get; };
    
    public CanvasViewModel()
    {
        Points = new(Database.GetPoints());
    }

    public void DrawLine()
    {
        System.Random rand = new();
        Point p = new(rand.Next(101), rand.Next(101));
        Points.Add(p);
        this.RaisePropertyChanged(nameof(Points));
        
        System.Diagnostics.Debug.WriteLine(p); // shows that the point is actually created and added to the collection
    }
}

Database.GetPoints()返回一个IEnumerable<Point>

4

0 回答 0