What can I do if I want to have a text-box representing in real time the value of a loop counter in wpf?
appending working solution:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private delegate void UpdateTextBox(DependencyProperty dp, Object value);
...
private void MyMethod()
{
...
int iMax=...;
...
MyClass iMyClass = new MyClass(arguments);
this.DataContext = iMyClass;
UpdateTextBox updateTBox = new UpdateTextBox(textBlock1.SetValue);
for (int i = 1; i <= iMax; i++)
{
iMyClass.MyClassMethod(i);
Dispatcher.Invoke(updateTBox, System.Windows.Threading.DispatcherPriority.Background, new object[] { MyClass.MyPropertyProperty, iMyClass.myProperty });
}
Here is the code I tried according to your suggestion, but it doesnt work, I get "0" written in the textbox, so I suppose the binding is OK, but the loop doesnt work. I also made the loop to write into another textbox directly by textbox2.text="a" inside the loop, but it didnt work either.
/// <summary>
/// Interaction logic for Window1.xaml
/// DOESNT WORK PROPERLY
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
TestClass tTest = new TestClass();
this.DataContext = tTest ;
tTest.StartLoop();
}
}
public class TestClass : DependencyObject
{
public TestClass()
{
bwLoop = new BackgroundWorker();
bwLoop.DoWork += (sender, args) =>
{
// do your loop here -- this happens in a separate thread
for (int i = 0; i < 10000; i++)
{
LoopCounter=i;
}
};
}
BackgroundWorker bwLoop;
public int LoopCounter
{
get { return (int)GetValue(LoopCounterProperty); }
set { SetValue(LoopCounterProperty, value); }
}
public static readonly DependencyProperty LoopCounterProperty = DependencyProperty.Register("LoopCounter", typeof(int), typeof(TestClass));
public void StartLoop()
{
bwLoop.RunWorkerAsync();
}
}
}