0
我無法通過綁定更新WorkerThread的PolyLine,方法是更新Dispatcher中的Source。它只適用於從WorkerThread更新PolyLine.Points PointCollection,但它不會如果我將Polyline.Points綁定到另一個PointCollection,然後從WorkerThread更新。 但是,我沒有得到任何例外,我可以在PolyLine.Points和BindingSource中看到這些點,但是永遠不會在屏幕上顯示它。 僅在UIThread上運行代碼時,綁定工作正常。WPF - 綁定和調度程序
這將是很好如果有人可以向我解釋這種行爲並告訴我如何解決這個問題, 謝謝!
在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(""));
}
}
}
我做到了,但它沒有任何效果。正如我所說的,如果一切都在UIThread中完成的話,綁定工作。 – user3485988