【问题标题】:WPF - Binding and DispatcherWPF - 绑定和调度程序
【发布时间】:2014-04-02 00:55:31
【问题描述】:

我无法通过从调度程序更新源来通过绑定更新 WorkerThread 的折线。它仅在我从 WorkerThread 更新 PolyLine.Points PointCollection 时才有效,但如果我将 Polyline.Points 绑定到另一个 PointCollection,然后从 WorkerThread 更新它,则它不起作用。 但是我没有任何异常,我可以在 PolyLine.Points 和 BindingSource 中看到点,但从未出现在屏幕上。 仅在 UIThread 上运行代码时,Binding 工作正常。

如果有人可以向我解释这种行为并告诉我如何解决这个问题,那就太好了, 谢谢!

在 XAML 中它们只是一个按钮和一个画布

public partial class MainWindow : Window
{
    PointCollection bindingPoints;
    Polyline line;
    Dummy dummy;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    { 
        dummy = new Dummy();
        dummy.PropertyChanged += dummy_PropertyChanged;

        line = new Polyline();
        line.Stroke = Brushes.Black;
        line.StrokeThickness = 2.0;
        this.canvas.Children.Add(line);

        bindingPoints = new PointCollection();
        Binding bind = new Binding();
        bind.Mode = BindingMode.OneWay;
        bind.Source = bindingPoints;
        //line.SetBinding(Polyline.PointsProperty, bind); //<= If Binding is Set, direct Adding fails



        Thread t = new Thread(new ThreadStart(dummy.Move));
        t.Start(); //<= Works for direct Adding only
        //dummy.Move(); //<= Works for Binding an direct Adding
    }

    void dummy_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        Dummy d = sender as Dummy;

        this.Dispatcher.Invoke((Action)(() =>
        {
            //line.Points.Add(new Point(d.P.X, d.P.Y)); //<= direct Adding
            bindingPoints.Add(new Point(d.P.X, d.P.Y));
        }));
    }
}


public class Dummy : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Point p;

    public Point P
    {
        get { return p; }
        set
        {
            p = value;
            OnPropertyChanged();
        }
    }

    public void Move()
    {
        Random rnd = new Random();

        int i = 0;
        do
        {
            this.P = new Point( i + rnd.Next(1, 10), rnd.Next(i, 250));
            Thread.Sleep(rnd.Next(60));
            i++;
        } while (i < 250);
    }

    protected void OnPropertyChanged()
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(""));
        }
    }
}

【问题讨论】:

    标签: wpf binding dispatcher


    【解决方案1】:

    你只能绑定到属性,把它改成一个属性:

    PointCollection bindingPoints;
    

    【讨论】:

    • 我做了,但没有效果。正如我所说,如果一切都在 UIThread 中完成,绑定就可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2016-11-01
    • 2013-02-07
    • 1970-01-01
    • 2012-09-13
    • 2011-12-27
    • 1970-01-01
    相关资源
    最近更新 更多