需要用最简单的方式(我认为应该是折线)在WPF中使用MVVM模式绘制2D图形。我已经创建了几个类:
在 App.xaml 中。
在MainWindow.xaml文件中。
namespace SomeNamespace.Models
{
class Info
{
// public Queue<int> Dots { get; set; }???
public int Point { get; set; }
public int GetLoad()
{
return new Random (100); //Get some data from external class
}
}
}
namespace SomeNamespace.ViewModels
{
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
class InfoViewModel: ViewModelBase
{
//private Queue<Point> _dots = new Queue<Point>();
//public Queue<int> Dots
//{
// get { return _dots; }
// set
// {
// _dots = value;
// OnPropertyChanged("Dots");
// }
//}
private int _point;
public int Point
{
get { return _point; }
set
{
_point = value;
OnPropertyChanged("Point");
}
}
}
class MainViewModel : ViewModelBase
{
// public ObservableCollection<InfoViewModel> InfoList { get; set; }??
public ObservableCollection<int> Points { get; set; }
public MainViewModel(List<Info> info)
{
//InfoList = new ObservableCollection<InfoListViewModel>(info.Select i => new InfoViewModel( i)));???
Points = new ObservableCollection<int>() { 10, 20, 30, 40 }; //just for test
}
}
}
在 App.xaml 中。
public partial class App : Application
{
private void OnStartup(object sender, StartupEventArgs e)
{
List<Info> i = new List<Info>()
{
new Info(){ Point = 10 },
new Info(){ Point = 15 },
new Info(){ Point = 20 },
new Info(){ Point = 25 },
new Info(){ Point = 30 },
new Info(){ Point = 35 }
};
MainWindow mainView = new MainWindow();
MainViewModel mainViewModel = new MainViewModel( i);
mainView.DataContext = mainViewModel;
mainView.Show();
}
}
在MainWindow.xaml文件中。
<Grid>
<Polyline Name="graph1" Fill="Blue"
Points="{Binding Points}" Stroke="Blue" >
</Polyline>
</Grid>
但它不起作用。
编辑:
我写了以下代码,但我不明白:
1)如何将<Line X1="{Binding ??}" Y1="{Binding ??}" X2="{Binding ??}" Y2="{Binding ??}" Stroke="Red"/>
绑定到Queue<Point>?
2)如何使< Line .../>
每秒刷新一次?或者如何让ViewModel每秒自动刷新并通知View?
public class Segment
{
public Queue<Point> Dots { get; set; }
}
public class ViewModel:INotifyPropertyChanged
{
private Queue<Segment> _segments;
public Queue<Segment> Segments
{
get { return _segments; }
set
{
_segments = value;
OnPropertyChanged("Segments");
}
}
public ViewModel(Queue<Point> segments)
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainWindow mainView = new MainWindow();
Queue<Point> q = Class1.GenerateData(); //Class1.GenerateData() returns Queue<Point>
mainView.DataContext = new ViewModel(q);
ViewModel
实现INotifyPropertyChanged
接口,特别是针对Segments
。 - Rick Sladkey