Tuesday, November 24, 2009

Useful code snippets for WPF developer.

Download snippets - here

I want to share very useful in my opinion code snippets for WPF developers. Most of they were created my friend - Dmitrij Zakharov. Moreover I want to add a short description to each snippets.

Note:
The Code Snippet Inserter inserts a code snippet at the cursor location, or inserts a surround-with code snippet around the currently selected code.

Don't you know how to use code snippets? You should read next article - How to: Use Code Snippets (C#). You should copy the code snippets files to Installation directory\Microsoft Visual Studio 9.0\VC#\Snippets\1033\NetFX30 in your PC for start to use.

Let me start:
  • addowner - Adds owner to the dependency property that already exists.
  • defstyle - Code snippet for overriding DefaultStyleKey.
  • propa - Code snippet for an attached property using DependencyProperty as the backing store. It is the common code snippet that is delivered with installation of VS2008
  • propdp - Code snippet for a property using DependencyProperty as the backing store. It is the common code snippet that is delivered with installation of VS2008
  • propdpec - Code snippet for a property with value caching and events support using DependencyProperty as the backing store.
  • propdpr - Code snippet for a property using DependencyPropertyKey as the backing store.
  • routedcmd - Implements routed command executor.
  • routedevent - Declares and implements routed event.
PS: Do you want to know more? - read about Default Code Snippets.

Thursday, November 19, 2009

Zoom and page changed events for FlowDocumentPageViewer

Download source files - here

My old known Bala send to me this link.
Kent Boogaart has written an article that describes approach searching and highlighting text in FlowDocumentPageViewer - Search and Highlight Text in an Arbitrary Visual Tree. Unfortunate, two serious issues present there. I copy theirs description from msdn forum:
  1. When I change the pages of the FlowDocumentPageViewer, my Rectangular highlighted area remains the same and it is not sinking with the Text.
  2. When I zoom in or zoom out of the FlowDocumentPageViewer, the text gets zoomed but the Highlight rectangle remains in the same position.
Seems.. solution should be easy - just add DoSeach() method in PageChanged and ZoomChanged event handler methods of FlowDocumentPageViewer but it doesn't have events for notice these actions. So I decided just to implement these events :). FlowDocumentPageViewer doesn't have protected and virtual methods like OnZoomChanged or OnPageChanged. It was bad. But I found four protected and virtual methods that could help me they are OnNextPageCommand(), OnPreviousPageCommand(), OnIncreaseZoomCommand() and OnDecreaseZoomCommand(). When I added call to rise my events in theirs override methods I found that this approach wasn't work. It happened because command logic works through concurrency approach. I called the rise methods through BeginInvoke for delay the calls rise methods - and problem was solved.
You can download sources with fix above.

PS: I didn't have time for full investigate sources.. but one question. Why did Kent use SearchRectangle class? In my opinion common Rect is enough.

Monday, November 16, 2009

How to implement TextBox with PlaceHolder in WPF

Download source files - here

Using PlaceHolder is very useful thing for UI in any type application. I want to show a short way how can you implement it in WPF.
You can custom TextBox and add place-holder text on MouseEnter and remove on MouseLeave events. In this case place-holder's text looks like original text.. You can experiment with Foreground property, but truth me - you will not be satisfy.
Let my suggest other way. You can use AdornerLayer for host the place-holder text. In this case you should create class that is inherit from Adorner and this class should show your place-holder text on AdornerLayer. I've create little sample that demonstrate this.

Unfortunate, AdornerLayer doesn't presented over any Popup controls. So this solution isn't worked if you put our customized TextBox control in any Popup and as item in Menu or ComboBox controls.

Friday, October 16, 2009

Performance degrades in your Silverlight App!? What can you do?


Some time ago I had written Silverlight app and I confronted with difficulties of difference between WPF and Silverlight :). When I had vanquished mismatches I found that performance of my app was serous degraded. I have done a little investigate of ways that can help to correct this issues.
  1. MaxFrameRate
  2. EnableGPUAcceleration & BitmapCash
  3. CompositionTarget.Rendering
MaxFrameRate - presents the maximum number of frames that Silverlight can render per second. The default value is 60 second. I've set 30 in my app - looks pretty. This property likes DesiredFrameRate in WPF. Target is clear - reduce frame rate. It is useful when more animations are started in Silverlight app.
You can set it from Silverlight code:

App.Current.Host.Settings.MaxFrameRate=30;

or as parameter of object on HTML page:

<param name="framerate" value="30">

Pay attention there is a mismatch naming in Silverilght code and HTML. Why is it? You can read there.

EnableGPUAcceleration & BitmapCash - allows to cache visual object when it is possible. You should switch on EnableGPUAcceleration that Cache has any effect. This approach is useful when your app has opacity or transform operations applied to it.
You can set it from Silverlight code:

You can't change it from Silverlight because it should be set before app's initialization.

or as parameter of object on HTML page:

<param name="EnableGPUAcceleration" value="true" />

and set CacheMode. In current moment BitmapCache is supported only.
You can set it in C# code:

LayoutRoot.CacheMode = new BitmapCache();

or in XAML:

<Grid x:Name="LayoutRoot" CacheMode="BitmapCache">

Some objects don't look well (high-resolution images for example) you can increase RenderAtScale property of BitmapCache class for avoid this mess. Default value of this property is 1, when I set 4 (like MSDN's samples) quality restores but performance degrades again. A value between 2-3 is god for my app.
You can set it in C# code:

LayoutRoot.CacheMode = new BitmapCache
{
RenderAtScale = 2.5,
};


or in XAML:

<Grid x:Name="LayoutRoot">
<Grid.CacheMode>
<BitmapCache RenderAtScale="2.5" />
</Grid.CacheMode>
</Grid>


CompositionTarget.Rendering - this event rises before the objects in the composition tree are rendered. How does it can help? In common case - doesn't. But if you zoom your object in app (or in same other manner move out of bounds some item) - it is very useful. Look in my case:
First - subscribe event handler's method in constructor of your main window:

CompositionTarget.Rendering += new EventHandler( OnCompositionTargetRendering );

Second - handler method:

private void OnCompositionTargetRendering( object sender, EventArgs e )
{
//--- Start 1 -- //
foreach ( GalleryItem item in xGalleryCanvas.Children )
{
if ( Visibility.Collapsed == item.Visibility )
{
item.Visibility = Visibility.Visible;
}
}
//--- End 1 -- //
//--- Start 2 -- //
if ( _isZoomed && 0 < rect =" new" visibleitems =" VisualTreeHelper.FindElementsInHostCoordinates(" f =""> f.GetType() == typeof( GalleryItem ) );

foreach ( GalleryItem item in xGalleryCanvas.Children )
{
if ( !visibleItems.Contains( item ) )
{
item.Visibility = Visibility.Collapsed;
}
}
//--- End 2 -- //
}

Some explanation: You should ascertain that all items are visible (block 1).
Note: Dependency property works not so good as in WPF. So you should change Visibility only of collapsed items. In other case you serious reduce the performance.
Use mix of FindElementsInHostCoordinates() of VisualTreeHelper and LINQ for create collection all visible items in current moment and collapse all other items (block 2).

Promise these three approaches can help as these help me.

PS: Recently I've found useful tips of Silverlight performance. You can read it there - Performance Tips.

Wednesday, August 12, 2009

Trips&Ticks: Do you know how you can unsubscribe from anonymous method?

Anonymous Methods is a useful feature which we receive in Framework 2.0. It allows to easy pass a small code block as a delegate parameter (you can set a large block code but this code will be harmful because it is complex and isn't clear for perception). For example:
button1.Click += delegate
{
MessageBox.Show( "Anonymous" );
};
But I have one trouble. What can I do if I want to unsubscribe from event. Seems it is subscribed finally, isn't it?.. Noup! If we declare instance of delegate before define we can unsubscribe a event from this delegate in the code block. For example:
EventHandler handler = null;

handler = delegate
{
MessageBox.Show( "Anonymous" );
button2.Click -= handler;
};

button2.Click += handler;
So if we click on button1 we receive message box always. If we click on button2 we receive message box once.

Wednesday, July 29, 2009

LINQPad (new version) - nice tool that can help you to stady LINQ.

LINQPad is nice tool that can help you to study LINQ. I have read firs overview of this tool. Absence auto-complete grieves most people. Auto-complete is present in new version. This option requiring payment. IMHO: auto-complete is more detrimental than efficiency for studying (but very useful for work).
But I want say not about that. LINQPad is obtain other interesting feature. Author of this tool Joseph Albahari with your brother had written book "C# 3.0 in a Nutshell" and he added LINQ samples from this book to LINQPad. You can not only investigate different case moreover you can see how it look in lambda and IL code.


Investigate these samples in IL code should be very interesting ;)

Sunday, July 19, 2009

Do you know about LINQ that.. ?

Do you know about LINQ to SQL that attribute is more important than value? What is it mean? My friend have found interesting relation. He had written LINQ to SQL where he checked a column value to null but he was disappointed - it wasn't worked if it was need. He had null values in set but LINQ code didn't see they (He had written simple test code with foreach - it worked). After some investigate he has found that trouble in mapped data. Particular property was marked ColumnAttribute with set CanBeNull property false. So LINQ implicitly optimizes him code regards attribute's value (skips the check to null).
PS: It shows that we should be careful to small thing.. because small things can implicitly brings a big and strange problems.