0

我的目标是有一条折线,我可以在其中每 2 秒添加一个点,并且折线在 UI 中反映它。

我有一个折线,它使用值转换器绑定到 ObservableCollection,如下所示:

XAML

<Polyline Points="{Binding OutCollection,Mode=TwoWay,Converter={StaticResource pointConverter}}" Stroke="Blue" StrokeThickness="15" Name="Line2"  />

值转换器

 public class PointCollectionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        PointCollection outCollection = new PointCollection();
        if (value is ObservableCollection<Point>)
        {
            var inCollection = value as ObservableCollection<Point>;

            foreach (var item in inCollection)
            {
                outCollection.Add(new Point(item.X, item.Y));
            }
            return outCollection;
        }
        else
            throw new Exception("Wrong Input");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new Exception("Wrong Operation");
    }
}

在文件后面的代码中:

public MainWindow()
    {
        InitializeComponent();
        this.DataContext = vm;
        InitTimer();
    }

    private void InitTimer()
    {
        dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(TickHandler);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
        dispatcherTimer.Start();
    }
    int counter = 0;
    private void TickHandler(object sender, EventArgs e)
    {
        double val = (counter * counter) * (0.001);
        var point = new Point(counter, val);
        vm.OutCollection.Add(point);
        vm.OutCollection.CollectionChanged += OutCollection_CollectionChanged;         

        counter++;
    }

视图模型:

public class ViewModel : ViewModelBase
{
    public ObservableCollection<Point> OutCollection
    {
        get
        {
            return m_OutCollection;
        }

        set
        {
            m_OutCollection = value;
            this.OnPropertyChanged("OutCollection");
        }
    }

}

    private ObservableCollection<Point> m_OutCollection;


    public ViewModel()
    {

        OutCollection = new ObservableCollection<Point>();

    }

它不工作。任何帮助表示赞赏?!?

4

1 回答 1

0

我自己解决了。

ObservableCollection 可能没有帮助,但有帮助的是添加

Line2.GetBindingExpression(Polyline.PointsProperty).UpdateTarget();

在里面TickHandler()

于 2016-05-04T19:09:51.380 回答