Difference in Event Handling in Silverlight and WPF - Thread Affinity issues - wpf

I have been developing a Lync Silverlight application in Silverlight and now I am trying to shift it to WPF.
However, I am facing some thread affinity issues. For example I display the Lync client's state on my page in a textblock, and so in my code behind have wired a state changed event handler, that writes the new state into the textblock whenever the state of Lync client changes.
Now, this worked perfectly in silverlight but seemingly is not allowed in WPF.
Now my questions are:
How come it works in Silverlight bt not in WPF, even though Silverlight is supposed to be a subset of WPF?
Thread affinity is an important concept and I know we can use invoke dispatcher, but doesn't it just beat the concept of asynchronous programming in form of event handlers and callbacks?
I have a button defined in my XAML page, and the click event handler defined on it can access other UI elements, it does not suffer the problem outlined above.
But if I define a LyncClient instance in my code-behind, event handlers defined on it cannot access the UI elements. Why so, I detected no such difference between UIElements and other objects in Silverlight?

Based on above comments, I'll suggest the following "answer"...
I would guess it is more likely than not that there is some sort of different in the way that the SL API was written than that of the WPF api. That could explain the difference in the thread that is used when the API issues the callback. To verify this, you could:
Ask MS directly
Put some diagnostics code in your callback method to log the thread ID and compare that to the main thread of the application. Do this for both SL and WPF to see if they are the same or different threads.
Open the assemblies in Reflector to inspect how each API was written.
In terms of handling this specific situation, in your callback, you could:
Get the dispatcher object (different for SL than WPF) and always issue UI updates through Dispatcher.Invoke.
Use databinding and INotifyPropertyChanged to insulate the UI from the property. You could delcare a property on a ViewModel or in the code behind. Then bind the UI's textbox to that property. Databinding has some smarts in it that will automatically marshal property changes to the correct thread (in most cases anyway).
Hope that helps.

Related

MultiThread in WPF

I have several projects, each of thern have UserControl to manage them. All projects are in one solution and working simultaneously. all UserControls are in TabControl. But if one project don't handle his exception, all solution fail down. How can i run each UserControl in another Thread ?
I have several classes, they are models in MVVM. All of them have ViewModel and View. Now all classes start and workig in one thread. If one of then throw exception< all app will fail down. I want taht all models working in individual thread. But all Views of taht models are together in TabControl. How i can organize this sheme?
You can't. WPF has one, and only one, user interface thread. Modifying user interface elements from a background thread won't work and will raise an exception. (EDIT: This is not entirely correct, apparently it is possible to start individual windows in their own threads.)
If you have a problem with uncaught exceptions, have a look at the Application.DispatcherUnhandledException event, which allows you to register a central exception handler for your complete WPF application. If you set e.Handled = true;
at the end of your DispatcherUnhandledException handler, exceptions will cause your application to fall back to the user interface rather than terminating the application.
More information:
WPF global exception handler

regarding wpf dispatcher

I am new to WPF and have a question regarding dispatcher and Delegate.Invoke.
In a windows forms application, we can use the invoke method to make changes to UI controls from other threads. This works because invoke “executes the specified delegate on the thread that owns the control's underlying window handle” (as per msdn).
My question is:
Why doesn't Invoke work on WPF? It should be allowed to make changes to UI as the thread that owns the UI control gets to execute the delegate, but still it throws a runtime exception that “a thread is trying to modify an object that is owned by a different thread”.
How does the dispatcher manage to make changes to WPF controls while Invoke fails?
Is it possible to do cross thread programming in WPF without using dispatcher or background worker?
1) why doesn’t invoke work on wpf?
It works fine, but perhaps you're not using it correctly. I suggest you read the documentation
It should be allowed to make changes to UI as the thread that owns the UI control gets to execute the delegate, but still it throws a runtime exception that “a thread is trying to modify an object that is owned by a different thread”
Perhaps you created a UI object on a worker thread, then tried to add it to the main UI on the UI thread ? Without seeing your code, it's only a guess...
2)How does despatcher manage to make changes to wpf controls while invoke fails?
This question is not very clear, but it's probably related to the first question anyway...
3) Is it possible to do cross thread programming in wpf without using despatcher or background worker?
If you need to manipulate the UI from a worker thread, you have to use the dispatcher. BackgroundWorker also uses the dispatcher (indirectly, through the ISynchronizationContext interface) to raise events on the UI thread. There's no way around it.

WPF interactionRequests in PRISM

I have what, on the face of it, seems to be a really simple requirement - to be able to show a messagebox from within the view model of my WPF prism application.
Reading the documentation everything sounds good when I'm reading about Interaction Requests but I then find out that WPF doesn't support PopupChildWindowAction.
How are people getting around this. Basically I want a Messagebox in my shell module / or a infrastructure module that will subscribe to events and popup when that event is published.
Another issue I had was I want the popup to be centered on the parent window (the shell).
Just wondered how other people approached this. There seem to be a number of different ways to go but neither seem to fit the bill exactly.
From A CodePlex post by Karl Shifflet:
I've written a WPF version of the Interaction Request for my the Box MVVM Training here:
http://visualstudiogallery.msdn.microsoft.com/en-us/3ab5f02f-0c54-453c-b437-8e8d57eb9942
Install this Visual Studio Extension.
Create a new project with the MVVM Training Template.
Check out DialogInteractionRequestView.xaml and its implementation.
Cheers,
Karl
Use the RegionPopupBehavior from Prism 2.2 RI.
Use the EventAggregator in PRISM to subscribe to events, and have an in-memory presenter that listens for an event and then creates a view using the event data and calls ShowDialog on the view.
The dialog result can then be used to publish a 'response' event that would be routed back to the process that initiated the event that resulted in the display of the dialog.
Since PopupChildWindowAction is only in Silverlight, I have created my own PopupAction by inheriting from TriggerAction class and simply overridden body of Invoke() method to bring up a PopupWindow where I can pass any UserControl from xaml within the prism interaction trigger tag. From within ViewModel I am raising interactivity request event which triggers my PopupAction in view and opens the popup with desired user control being displayed onto it. Seems to work. I'll need to polish the example more. But here is a link -
http://wpfgrid.blogspot.com/2013/01/simple-prism-mvvm-way-to-display-dialog.html#step3

Silverlight MVVM question

I'm working on a project and learning SL/MVVM as I go. I'm using MVVM light and feel as if I have a decent grasp of things. I understand binding controls to the VM and also sending events/commands to the VM.
A few questions I have:
In an MVVM application how is the Application object accessed from the VM, for calling Application.Install or checking install state? Or do you just stick it in the code behind of a view for that case? I suppose this could be done through MVVM messaging but you'd still register a listener in the code behind.
I'm not sure if this can happen but how would one, from the VM, access a method from a View/Control(s) to do something that can't be accomplished through data binding or commanding/eventing? Is this where Dependency Object/Properties come into play?
The application should provide a service for obtaining the information relevant to the Application singleton; as with any data which could be used throughout the application; yours or the frameworks.
If you are ever needing to access a method on a UIElement/FrameworkElement/Control from the ViewModel that would be the point in looking into a custom Control or UserControl to provide the needed behavior. That is typically solved via Triggers and Behaviors.

Why do my Silverlight UIElements NOT have OnPreview events?

I'm building a custom Silverlight UserControl which needs to listen to events using Preview/Tunneling, but for some reason the compiler is telling me they are not recognized or accessible.
For example, I can add an event handler to MouseLeftButtonDown, but not PreviewMouseLeftButtonDown. This doesn't make sense because according to Microsoft (http://msdn.microsoft.com/en-us/library/system.windows.uielement_members(v=VS.100).aspx) all UIElements should have Preview events attached.
Any ideas as to why this is happening? I'm using Visual Studio 2010 Trial, Blend 4 RC and .Net 4, if that makes a difference.
Silverlight does not support preview events nor does it support routed events (bubbling/tunneling) except for a few core events.
If you are trying to create a control that works with both WPF and Silverlight, you will need to take a different approach. Depending on what you're trying to do, you may be able to accomplish what you want by rigging up a handler in code and specifying that you want handled events too.
// the last parameter indicates we want to receive events that
// were marked as e.Handled = true by other listeners
// this type of event handler can only be done in code
myUserControl.AddHandler(
UIElement.MouseLeftButtonDownEvent,
OnMouseLeftButtonDown,
true
);
You're looking at the help for WPF, not Silverlight. Silverlight is (mostly) a subset of WPF, and much of the functionality is missing.
The Silverlight UIElement help does not show those events, as they do not exist in Silverlight.

Resources