Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

2008-12-03

WPF applications and CA2104 rule

If you are using static fields such as:

 public static class Constants

    {

        public static readonly FontFamily MyFontFamily  = new  FontFamily("Segoe UI");

    }

with “{x:Static}” markup extensions such as:

FontFamily="{x:Static this:Constants.MyFontFamily  }"

you will get the following warning:

CA2104 : Microsoft.Security : Remove the read-only designation from 'Constants.MyFontFamily' or change the field to one that is an immutable reference type. If the reference type 'FontFamily' is, in fact, immutable, exclude this message.


If you remove the “readonly” modifier you get a different warning:

CA2211 : Microsoft.Usage : Consider making 'Constants.MyFontFamily' non-public or a constant.             

In order to solve the problem convert the field, to a property with get accessor only, such as:

public static FontFamily MyFontFamily

        {

            get

            {

                return new FontFamily("Segoe UI");

            }

        }

2008-03-13

Great blog for WPF Data Binding

Beatriz Costa works in the Data Binding Test Team and has great information for data binding.

2007-12-13

Wallpaper Generator

A nice WPF application that creates a wallpaper based on a photo folder.

Download the application from here.

FlowDocument and multiple threads

Recently, I try to use the FlowDocumentScrollViewer to display FlowDocument's. So I create WPF window application that creates and displays flow documents with FlowDocumentScrollViewer.





The refresh button clears the contents of the documentPanel, and creates and displays a random number of flow documents.





This works as expected and creates a random number of flow documents on window.
My next step is to make this work in asynchronous manner. How is that possible? Enter DispatcherObject and WPF Threading model.
The basic technique is to use the Dispatcher methods and delegates to do the heavy operations in a different thread.
To demonstrate this, I create a new "Refresh Async" button and modify the flow document creation to include a 5 sec Sleep.
The next step is to add the delegate and dispatcher calls. The refresh async button handler uses the Dispatcher to asynchronously call the GenerateAndShowFlowDocumentHandler method which creates and displays the flow document.







This also works fine.

The next step is to create the FlowDocument in a separete thread and use the main UI thread for UI update.





When I try this I get exceptions!.








To resolve this issue, I should serialize the FlowDocument as Memory stream since FlowDocument's seems that they can’t serialize themselves on different threads.
Add the following before passing the flow document.









And to the handler :





And it works great!!