Tuesday, February 5, 2013

WPF Ribbon WIndow - Binding Breaks on window resize

Ran into this really weird problem on a recent project.

In a WPF view I am using the ribbon toolkit  Something really weird  happened.  I had a combo box to a ribbon group.  I am using MVVM Light to implement the MVVM pattern inside my application.

After doing some research I found one entry on a MSDN forum here Binding Breaks that said this is a problem with the data context being lost when re-sizing the window.  This is a crazy scenario that should never happen.  In the post on MSDN they talk about over riding or changing code inside the ribbon toolkit.  I really did not want to do this.  Typically I avoid changing Microsoft or any third party code at nearly any cost.  It makes future support really hard.  And lets face it, I am not smarter that the team of Microsoft developers who build the library in the first place.

So I came up with a different solution.  If I was loosing data context why not just set data context explicitly on the combo box that was loosing data context.  And it worked

Here is a little sample of what I did.  In this sample I have a view (XAML File) and a view model and a static view model locator class to bind the views to the view models.  Following standard MVVM Light pattern.

Here is a small sample of my adding data context.


<pre  style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoK_rOlCI0o8qqpoZvNwQ4r3ruEEUmcSnoNGvNK2_FdnjlRLIHVr8LjTb6W7VmWREvNm4nqfMcDkgi3GS0krWTPIi2-6AoL7vSnWO1fgf9K5WRLKBo0AxBpZ_REEbAssDJ3yrIb_4mnzeT/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> DataContext="{Binding ViewModel, Source={StaticResource Locator}}"

So Normally I would not set my data context on the element, but just once for the entire page.  But adding the data context binding simply fixes this issue.  Much easier than modifying Microsoft code.

No comments:

Post a Comment