I am opening WPF Window from Winforms application in manuItem_ClickedHandler.
Step 1:
In Constructor of ViewModel I am creating thread and doing some work. In callback event, Value of control is updated successfully.
Step 2:
I closes this WPF form and Re-Open the WPF Window. Thread again Runs and complete it work but this time Text on WPF GUI is not updated. Callback is called. but no Error and No GUI updated.
What I have tried:
View Model
public class MyViewModel : BindableBase
{
internal ThreadClass objThreadClass;
string statusText = $"The Time is: {DateTime.Now}";
public SynchronizationContext ViewContext;
public string StatusText
{
get => statusText;
set => SetProperty(ref statusText, value);
}
public MyViewModel()
{
objThreadClass = new ThreadClass();
Events_Delegates.evDisplayStatus += Events_Delegates_evDisplayStatus;
}
void Events_Delegates_evDisplayStatus(int count)
{
ViewContext.Post(x => StatusText = $"Current Count is: {count}");
}
}
//
ThreadClass
//
public class ThreadClass
{
Thread objThread;
Events_Delegates EvDel = new Events_Delegates();
public ThreadClass()
{
objThread = new Thread(ExecuteMethod);
objThread.Start();
}
void ExecuteMethod()
{
int i = 0;
int j = 0;
while (true)
{
while (i < 1000)
{
i++;
}
i = 0;
j++;
EvDel.DisplayStatus(j);
Thread.Sleep(500);
}
}
}
public class Events_Delegates
{
public delegate void dUpdateStatus(int count);
public static event dUpdateStatus evDisplayStatus;
public void DisplayStatus(int count)
{
evDisplayStatus(count);
}
}
//
View
<pre><Window x:Class="Abc.View.WinMultiThread"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Abc.View"
xmlns:dc="clr-namespace:Abc.ViewModel"
mc:Ignorable="d"
Title="Multi Threading" Height="1200" Width="2000" WindowState="Maximized" >
<Window.DataContext>
<dc:My_ViewModel/>
</Window.DataContext>
<Grid>
<Label Grid.Column="1" FontSize="18" FontWeight="Bold" Foreground="White" Background="OrangeRed" VerticalAlignment="Center" Content="{Binding StatusText}" ></Label>
</Grid>
</Window>
//
Code Behind
public partial class WinMultiThread : Window
{
My_ViewModel dataContext = null;
public WinDashboard()
{
InitializeComponent();
dataContext = (My_ViewModel)this.DataContext;
dataContext.ViewContext = SynchronizationContext.Current;
}
}
//
Code to Open Wpf Form from Winform Button
Abc.View.WinMultiThread wpfwindow = new Abc.View.WinMultiThread();
ElementHost.EnableModelessKeyboardInterop(wpfwindow);
wpfwindow.Show();