<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Derik Whittaker : HowTo, Silverlight</title><link>http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/Silverlight/default.aspx</link><description>Tags: HowTo, Silverlight</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Using MVVM with the AutoCompleteTextBox in Silverlight 4</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2011/11/18/using-mvvm-with-the-autocompletetextbox-in-silverlight-4.aspx</link><pubDate>Fri, 18 Nov 2011 22:25:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:68404</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=68404</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=68404</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2011/11/18/using-mvvm-with-the-autocompletetextbox-in-silverlight-4.aspx#comments</comments><description>&lt;p&gt;The AutoCompleteTextBox is a great tool in Silverlight to allow you to provide relevant information to your users as they are typing as seen below:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_4B1A6A5F.png"&gt;&lt;img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="image" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_4AAE376A.png" height="165" width="364" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;But there are a few issues with this control&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Pretty much every sample on the net uses the code behind to do the heavy lifting and not binding &lt;/li&gt;
&lt;li&gt;It will not update the VM text box in real time, which is needed if you want to do on the fly filtering &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this post I will walk you though how to setup your AutoCompleteText&amp;nbsp; box and we will learn how to do 3 things&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Use MVVM to populate and use the control &lt;/li&gt;
&lt;li&gt;Use a custom Behavior to allow the property backing the control to be updated in real time &lt;/li&gt;
&lt;li&gt;Use a command to trigger background searches on the fly &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;b&gt;Using MVVM to populate your control:&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;In order to populate your AutoCompleteTextBox you will need to bind something to the ItemSource property of the control as such:&lt;/p&gt;
&lt;p&gt;&lt;i&gt;ItemsSource=&amp;quot;{Binding KeywordSearchSource}&amp;quot;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;I am sure you are wondering what the KeywordSearchSource is?&amp;nbsp; Well it is simple a property which returns a IEnumerable&amp;lt;string&amp;gt;&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;       public IEnumerable KeywordSearchSource
        {
            get
            {
                return SomeListOfValues.Select( x =&amp;gt; x.TextValue );
            }
        }&lt;/pre&gt;
&lt;p&gt;The next thing you will want to do is setup a property in your view to handle the current value inside the control.&amp;nbsp; This is needed because we are binding and not using the code behind.&amp;nbsp; You can do this as below:&lt;/p&gt;
&lt;p&gt;&lt;i&gt;Text=&amp;quot;{Binding KeywordSearchText, Mode=TwoWay}&amp;quot;&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;The trick to above is to remember to mark this as being TwoWay or you will not get the results you are expecting&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;        private string _keywordSearchText;
        public string KeywordSearchText
        {
            get { return _keywordSearchText; }
            set 
            {
                _keywordSearchText = value; 

                NotifyOfPropertyChange(() =&amp;gt; KeywordSearchText); 
            }
        }&lt;/pre&gt;
&lt;p&gt;That does it for the MVVM portion of the setup.&amp;nbsp; However, you may already know that when binding to a text box the actual binding does not trigger until AFTER the user leaves the control, in many cases this is good but not in our case.&amp;nbsp; In our case I want to start the filter process as the user types (which is fine as I have all the filter data local, this is NOT fine if I have to do any type of remote call to filter the data as this will cause a bad user experience).&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Triggering the binding in real time:&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;As I stated above the binding of a text box (or autocomplete text box) does not fire until you leave the control and this is not the desired action for us.&amp;nbsp; In order to get around this we are going to create a custom behavior to allow the text box binding to push the value into our property in real time.&lt;/p&gt;
&lt;p&gt;Our custom behavior is going to be called the ImmediateUpdateBehavior and the code can be found below.&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;    public class ImmediateUpdateBehavior : Behavior
    {
        protected override void OnAttached()
        {
            AssociatedObject.TextChanged += OnTextChanged;
        }

        void OnTextChanged(object sender, RoutedEventArgs e)
        {
            AssociatedObject.GetBindingExpression(AutoCompleteBox.TextProperty).UpdateSource();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.TextChanged -= OnTextChanged;
        }
    }&lt;/pre&gt;
&lt;p&gt;In the behavior above you can see that all we are pretty much doing is listing for the TextChanged event and forcing the binding to fire.&amp;nbsp; This is a nice way to do it when developing with MVVM.&lt;/p&gt;
&lt;p&gt;Once we have our behavior created we need to attach it to our AutoCompleteTextBox and that can be found below.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_2307BB40.png"&gt;&lt;img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="image" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_7BCD720A.png" height="73" width="324" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Triggering the filtering to fire as we type:&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;I am going to chose to do this via a Command.&amp;nbsp; I guess you could have the changing value of the property do the same thing but I typically am against doing this as I feel it is hiding the implementation details of the filtering.&amp;nbsp; I also feel that this can cause unwanted side effects in your code if you are not careful.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;In order to use the command I am going to use the EventTrigger behavior in silverlight to call my command.&amp;nbsp; You can see this XAML below.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_09338511.png"&gt;&lt;img style="background-image:none;border-right-width:0px;padding-left:0px;padding-right:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;padding-top:0px;" title="image" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_28E25ED9.png" height="98" width="644" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the XAML above you see I am calling the KeywordSearchFilterCommand.&amp;nbsp; This command will end up calling the code below&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;        private void KeywordSearchFilter()
        {
	    // Key here is i am simply notifying to rebuind these values and allowing the underlying methods to filter the data
            NotifyOfPropertyChange(() =&amp;gt; SomeListOfValues);
            NotifyOfPropertyChange(() =&amp;gt; PagedSomeListOfValues);
        }&lt;/pre&gt;
&lt;p&gt;As you can see from the above I am not doing anything special in the filter method I am simply notifying of property change and letting the various properties doing their own filtering.&amp;nbsp; The code below is the filtering for my PagedSomeListOfValues property (we are doing client side paging here)&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;        public ObservableCollection PagedSomeListOfValues
        {
            get
            {
                var skipCount = PageIndex &amp;gt; 0 ? PageIndex * PageSize : 0;
                var takeCount = PageSize;
                var tempItems= SomeListOfValues.Skip(skipCount).Take(takeCount).ToList();

                var observableLinks = new ObservableCollection();
                observableLinks.SetContents(tempItems);

                return observableLinks;
            }
        }&lt;/pre&gt;
&lt;p&gt;Once you have your 2 properties (list and search field) bound to the AutoCompleteTextBox you are almost there, but not quite.&amp;nbsp; In order to make this fully work you will want to also you the custom behavior and the filter command.&lt;/p&gt;
&lt;p&gt;Hope this helps.&lt;/p&gt;
&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=68404" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Silverlight/default.aspx">Silverlight</category></item><item><title>Getting around the Caching in the Silverlight Image Control</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2011/09/23/getting-around-the-caching-in-the-silverlight-image-control.aspx</link><pubDate>Fri, 23 Sep 2011 17:24:42 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:68197</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=68197</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=68197</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2011/09/23/getting-around-the-caching-in-the-silverlight-image-control.aspx#comments</comments><description>&lt;p&gt;Today I ran into a very odd issue when trying to reload the Silverlight Image Control with a new image which happened to have the EXACT same URL as the previously loaded image.&lt;/p&gt;  &lt;p&gt;See in our application we provide a way to upload an image and also allow the user to not simply create a new image but rather swap out an existing image with a new one but leave the URL the exact same.&amp;#160; During my development I really did not pay attention to or care that when I swapped out the image instance and raised the property changed event that the actual image was changing from the old to the new.&lt;/p&gt;  &lt;p&gt;When I noticed that this was not working as expected I assumed that I could kill the instance of the object which was being bound to the &amp;lt;Image /&amp;gt; control in Silverlight and reset it w/ the new instance and that would trigger the reloading of the image via its url, however as you may have guessed this did not work.&amp;#160; I had setup the binding to the control as follows:&lt;/p&gt;  &lt;p&gt;Source=&amp;quot;{Binding CurrentImage.SourceUrl}&lt;/p&gt;  &lt;p&gt;I liked the binding code above (loading via URL rather than binary data) because I could easily hook into the loaded/failed events of the control in order to indicate to the user that there was something wrong with the image they are using.&lt;/p&gt;  &lt;p&gt;It turns out (based on observations and Fiddler traces) that the Silverlight Image control will cache the current image and will NOT refresh/reload the image if the URL does not change.&amp;#160; I guess the assumption is that if the same URL is provided multiple times don’t to waste cycles reloading it to only show the same image which is in memory. &lt;/p&gt;  &lt;p&gt;This behavior works great in most cases…well until you don’t want it to work like this.&amp;#160; I thought of a few ways to get around this issue, such as binding to a BitmapImage or binding to a byte[] array.&amp;#160; However I really wanted to reduce the amount of rework or modifications I needed to make to the existing VM.&amp;#160; &lt;/p&gt;  &lt;p&gt;The solution we found that solved the issue was to bind to a image source url in the VM directly (did not want to dirty the existing SourceUrl Property as others user it and this work around is PURELY as UI issue, not a domain one) to a Url property in the VM and append an arbitrary query string value to the end of the URL.&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;       public string CurrentImageSourceUrl
        {
            get
            {
                if (CurrentImage != null)
                {
                    return string.Format(&amp;quot;{0}?id={1}&amp;quot;, CurrentImage.SourceUrl, Guid.NewGuid().ToString());
                }

                return string.Empty;
            }
        }&lt;/pre&gt;

&lt;p&gt;When I added the querystring value as above I was able to leave my existing VM logic alone and have the Image control reload the image correctly because it assumed that since my URL has changed that the images are different. I know this is a bit of a hack but hey it worked &lt;img style="border-bottom-style:none;border-left-style:none;border-top-style:none;border-right-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/wlEmoticon_2D00_smile_5F00_7B2663D7.png" /&gt; .&amp;#160; If anyone knows of a better way to solve this please let me know.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=68197" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Silverlight/default.aspx">Silverlight</category></item><item><title>Convention Based View Model Location using Ninject in a MVVM/Silverlight Application</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2011/07/02/view-model-location-using-ninject-in-a-mvvm-silverlight-application.aspx</link><pubDate>Sat, 02 Jul 2011 11:23:53 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:67852</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=67852</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=67852</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2011/07/02/view-model-location-using-ninject-in-a-mvvm-silverlight-application.aspx#comments</comments><description>***** UPDATE *****   &lt;br /&gt;If you would like to see a video on this topic check out &lt;a href="http://dimecasts.net/Casts/CastDetails/194"&gt;Episode 194 @ Dimecasts.Net&lt;/a&gt;   &lt;br /&gt;*******************  &lt;p&gt;When building out a Silverlight application (or WPF application for that matter) the &lt;a href="http://en.wikipedia.org/wiki/Model_View_ViewModel"&gt;MVVM&lt;/a&gt; pattern is the pattern of choice for most projects I am aware of.&amp;#160; When using MVVM there is a sub pattern which is commonly used which is known as ViewModelLocator.&amp;#160; The ViewModelLocator concept basically tries to handle the repetitive task of coupling the View with its ViewModel but doing so in a way which removes any manual coding and it just ‘happens’.&lt;/p&gt;  &lt;p&gt;Now if you have done any research on the ViewModel Location I am sure you have run across countless other blog posts out there which explain how to implement in this code, and many of them are great.&amp;#160; In fact here are a few which helped me down the path of creating the code I am going to talk about in this post&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://johnpapa.net/simple-viewmodel-locator-for-mvvm-the-patients-have-left-the-asylum"&gt;Simple ViewModel Locator&lt;/a&gt; for MVVM by John Papa (this is the post which really kick started this pattern) &lt;/li&gt;    &lt;li&gt;Wiring up &lt;a href="http://blog.roboblob.com/tag/viewmodellocator/"&gt;ViewModel Locator&lt;/a&gt; w/ Silverlight &lt;/li&gt;    &lt;li&gt;MVVM and &lt;a href="http://geekswithblogs.net/bdiaz/archive/2010/03/31/kiss-and-tell---mvvm-and-the-viewmodellocator.aspx"&gt;ViewModel Location&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Another MVVM and &lt;a href="http://geekswithblogs.net/bdiaz/archive/2010/03/31/kiss-and-tell---mvvm-and-the-viewmodellocator.aspx"&gt;ViewModel Location&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://caliburnmicro.codeplex.com/"&gt;Caliburn.Micro&lt;/a&gt; has an implementation &lt;/li&gt;    &lt;li&gt;&lt;a href="http://mvvmlight.codeplex.com/"&gt;MVVMLight&lt;/a&gt; has an implementation &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;All of the above posts basically show how to implement this pattern in your application and from what I can tell all of them work and will do the job. However, none of those (minus the Caliburn.Micro) implementations fulfills the one requirement I want which is to totally remove the need to ‘wire’ the ViewModel up to your View if even via XAML.&amp;#160; I want to remove this wiring from the XAML because in my mind this still leaves me hard wiring the relationship rather than using convention based wiring.&amp;#160; One scenario in which the hard wiring could turn around and bite you is in the times where you rename the view and the view model.&amp;#160; If you fail to update your wiring code in XAML you will receive runtime errors.&lt;/p&gt;  &lt;p&gt;Here are a few examples:    &lt;br /&gt;John Papa’s Implementation&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;DataContext=&amp;quot;{Binding Source={StaticResource VMLocator}, Converter={StaticResource VMIndexerConverter}, ConverterParameter=MainPageViewModel}&amp;quot;&lt;/pre&gt;

&lt;p&gt;ViewModelLocator’s Implementation&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;    &amp;lt;UserControl.Resources&amp;gt;
        &amp;lt;ViewModels:EditUsersViewModelLocator x:Key=&amp;quot;viewModelLocator&amp;quot;  /&amp;gt;
    &amp;lt;/UserControl.Resources&amp;gt;
    &amp;lt;UserControl.DataContext&amp;gt;
        &amp;lt;Binding Source=&amp;quot;{StaticResource viewModelLocator}&amp;quot; Path=&amp;quot;ViewModel&amp;quot; /&amp;gt;
    &amp;lt;/UserControl.DataContext&amp;gt;&lt;/pre&gt;

&lt;p&gt;I wanted my implementation of toe ViewModelLocator pattern to NOT need to know anything about the actual View or the ViewModel either in the XAML or in the code behind.&amp;#160; What I wanted as the following:&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;DataContext=&amp;quot;{Binding Source={StaticResource VMLocator}, Converter={StaticResource VMIndexerConverter}}&amp;quot;&lt;/pre&gt;

&lt;p&gt;Now you may be looking at my XAML above and comparing it to the XAML from John Papa’s post and be thinking what is really different?&amp;#160; The difference is in this segment of code &lt;em&gt;ConverterParameter=MainPageViewModel &lt;/em&gt;In his example he ‘hard wires’ the ViewModel which is being used up to the page and I did not want to do that.&amp;#160; I wanted to use a standard naming convention (right, &lt;a href="http://en.wikipedia.org/wiki/Convention_over_configuration"&gt;convention over configuration&lt;/a&gt;) and allow my locator to determine the ViewModel based on the current View.&lt;/p&gt;

&lt;p&gt;So how did I implement my ViewModelLocator pattern, well lets take a look.&lt;/p&gt;

&lt;p&gt;Code for ViewModelLocator&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public class ViewModelLocator
{   
    private static readonly IDictionary&amp;lt;type, type&amp;gt; s_viewModelCache = new Dictionary&amp;lt;type, type&amp;gt;();
        
    public Type GetViewModelTypeForView( Type viewType )
    {
        var viewModelName = ResolveViewModelName(viewType.Name).ToLower();

        // We are try to cache the types in order to remove the assembly scan hit, this is optional of course and 
	// you may not want or need this
	// One thing to point out here is that this code ASSUMES that your view and viewmodel classes are in the 
	//  same assembly.  if this is not true for your project this code will not work as expected.  We made this
	//  assumption because it is true in our project
        var foundViewModelType = GetExistingTypeFromCache(viewType) ?? (from type in viewType.Assembly.GetExportedTypes()
                                                                        where viewModelName.Equals(type.Name.ToLower())
                                                                        select type).FirstOrDefault();
    
        // this will throw a custom exception type, you can use your own if you want
        if (foundViewModelType == null) { throw new ViewModelTypeNotResolvedException(viewModelName, viewType); }

        // Add the found view and viewModel to the cache
        AddToCache(viewType, foundViewModelType);

        return foundViewModelType;
    }

    private void AddToCache(Type viewType, Type foundViewModelType)
    {
        if (!s_viewModelCache.ContainsKey(viewType))
        {
            s_viewModelCache.Add(viewType, foundViewModelType);
        }
    }

    private Type GetExistingTypeFromCache( Type viewType )
    {
        if (s_viewModelCache.ContainsKey(viewType))
        {
            return s_viewModelCache[viewType];
        }

        return null;
    }

    private string ResolveViewModelName(string viewTypeName)
    {
        var asLowerViewTypeName = viewTypeName.ToLower();

	// ***** Below is OUR product&amp;#39;s current naming conventions, replace with your own if you want *****
        // check to see if the view ends w/ &amp;quot;View&amp;quot;
        if (asLowerViewTypeName.EndsWith(&amp;quot;view&amp;quot;))
        {
            return asLowerViewTypeName.Replace(&amp;quot;view&amp;quot;, &amp;quot;ViewModel&amp;quot;);
        }

        if (asLowerViewTypeName.EndsWith(&amp;quot;usercontrol&amp;quot;))
        {
            return asLowerViewTypeName.Replace(&amp;quot;usercontrol&amp;quot;, &amp;quot;ViewModel&amp;quot;);
        }

        if (asLowerViewTypeName.EndsWith(&amp;quot;childwindow&amp;quot;))
        {
            return asLowerViewTypeName.Replace(&amp;quot;childwindow&amp;quot;, &amp;quot;ViewModel&amp;quot;);
        }

        return string.Concat(viewTypeName, &amp;quot;ViewModel&amp;quot;);
    }

    public static IDictionary&amp;lt;type, type&amp;gt; ViewModelCache { get { return s_viewModelCache; } }
}&lt;/pre&gt;

&lt;p&gt;Code for IndexConverter&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public class IndexerConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    {
        Contract.Requires&amp;lt;ArgumentNullException&amp;gt;(value != null);

        var locator = value as ViewModelLocator;

        Contract.Assume(locator != null,
                        string.Format(
                            &amp;quot;The provided converter value was expected to be of type {0} but was provided as type {1} which is not acceptable for this converter&amp;quot;,
                            typeof(ViewModelLocator).Name,
                            value.GetType().Name));

        var viewType = GetViewType();

        var viewModelType = locator.GetViewModelTypeForView(viewType);

	// We are using the ServiceLocator pattern which is wrapping Ninject
        var viewModelInstance = ServiceLocator.Current.GetInstance(viewModelType);

        return viewModelInstance;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
        
    // This does incur a perf hit by looking at the stack trace, but in 
    //  my opinion this hit is worth it compared to having to manually wire items up
    private Type GetViewType()
    {
        var stack = new StackTrace();

        return stack.GetFrames()
            .Select(f =&amp;gt; f.GetMethod())
            .Where(m =&amp;gt; m.Name == &amp;quot;InitializeComponent&amp;quot;)
            .Select(m =&amp;gt; m.DeclaringType)
            .FirstOrDefault();
    }

}&lt;/pre&gt;

&lt;p&gt;Code needed in your App.Xaml&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;&amp;lt;MVVMLib:ViewModelLocator x:Key=&amp;quot;VMLocator&amp;quot; /&amp;gt;
&amp;lt;MVVMLib:IndexerConverter x:Key=&amp;quot;VMIndexerConverter&amp;quot; /&amp;gt;&lt;/pre&gt;

&lt;p&gt;Code for the custom Exception ViewModelTypeNotResolvedException&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;public class ViewModelTypeNotResolvedException : Exception
{
    public string ViewModelName { get; set; }
    public Type ViewName { get; set; }

    // Commented this out because i do not want to be able to create this without the VMName or the VName
    //public ViewModelTypeNotResolvedException() {}

    /// 
    /// Will build an instance of the exception and push in a default message based on the viewModelname and view properties.
    /// *** This is the lazy way to create the message ***
    /// 
    /// &lt;param name="viewModelName" /&gt;The name of the viewModel which was not able to be created or found&lt;/param&gt;
    /// &lt;param name="view" /&gt;The type for the view we were trying to bind the VM to&lt;/param&gt;
    public ViewModelTypeNotResolvedException(string viewModelName, Type view)
        : base(string.Format(&amp;quot;When trying to resolve the view model {0} it was not found in the same assembly as the view {1}&amp;quot;, viewModelName, view.Name))
    {
        ViewModelName = viewModelName;
        ViewName = view;            
    }

    /// 
    /// Will build an instance of the exception
    /// 
    /// &lt;param name="viewModelName" /&gt;The name of the viewModel which was not able to be created or found&lt;/param&gt;
    /// &lt;param name="view" /&gt;The type for the view we were trying to bind the VM to&lt;/param&gt;
    /// &lt;param name="message" /&gt;&lt;/param&gt;
    public ViewModelTypeNotResolvedException(string viewModelName, Type view, string message) : base(message)
    {
        ViewModelName = viewModelName;
        ViewName = view;
    }

    /// 
    /// Will build an instance of the exception
    /// 
    /// &lt;param name="viewModelName" /&gt;The name of the viewModel which was not able to be created or found&lt;/param&gt;
    /// &lt;param name="view" /&gt;The type for the view we were trying to bind the VM to&lt;/param&gt;
    /// &lt;param name="message" /&gt;&lt;/param&gt;
    /// &lt;param name="innerException" /&gt;&lt;/param&gt;
    public ViewModelTypeNotResolvedException(string viewModelName, Type view, string message, Exception innerException)
        : base(message, innerException)
    {
        ViewModelName = viewModelName;
        ViewName = view;
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see the code needed for this is not that complicated or difficult to implement.&amp;#160; &lt;/p&gt;

&lt;p&gt;One thing to understand with this post, I am NOT saying that the other implementations are bad or they do not work. In fact I am saying the exact opposite, they all are great and they all work and I used all their implementations as baseline for my implementation.&amp;#160; What I am saying as the other examples did not meet my EXACT needs. &lt;/p&gt;

&lt;p&gt;Please take a look at the code and let me know where I went wrong or what your thoughts are.&amp;#160; &lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=67852" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Best+Practice/default.aspx">Best Practice</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/XAML/default.aspx">XAML</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Ninject/default.aspx">Ninject</category></item><item><title>How to determine if a View is loaded off of the Backstack in WP7</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2010/11/30/how-to-determine-if-a-view-is-loaded-off-of-the-backstack-in-wp7.aspx</link><pubDate>Tue, 30 Nov 2010 12:46:42 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:63693</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=63693</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=63693</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2010/11/30/how-to-determine-if-a-view-is-loaded-off-of-the-backstack-in-wp7.aspx#comments</comments><description>&lt;p&gt;One of the great features (also one which is not fully implemented in my opinion) is the backstack in WP7.&amp;#160; The idea of the back stack is that when you navigate away from a page that page is pushed to this stack so that when the user hits the back button (or it is done via code) the previous page can be reloaded off of the stack rather than being recreated.&lt;/p&gt;  &lt;p&gt;This is both a powerful as well as clumsy feature of WP7.&amp;#160; I say it is clumsy because there is nothing built into the framework (as far as I can tell) which tells you on page load if the page is being newly constructed or if it is being rehydrated via back navigation.&amp;#160; &lt;/p&gt;  &lt;p&gt;Because there are cases in our app that I want to know if the page is being accessed off of the backstack vs being newly created I set out to determine how I could build in the ability to detect this.&amp;#160; After a bit of research on google I was not able to find any solutions so I built my own.&amp;#160; Please note, that this may not be the best solution (I am open to hear about better ones) but it does appear to work.&lt;/p&gt;  &lt;p&gt;Before we dive into the logic used to determine how a view is being loaded we need to understand the some page life cycle events and the order in which they fire.&lt;/p&gt;  &lt;p&gt;Life cycle events for a newly constructed page (forward navigation)&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Page Constructor &lt;/li&gt;    &lt;li&gt;Page Loaded event fired &lt;/li&gt;    &lt;li&gt;Page Unloaded event fired (when you navigate away from the page) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Life cycle events for a page being rebuild off of the backstack (back navigation)&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strike&gt;Page Constructor &lt;/strike&gt;(this is NOT fired when being pulled off of the back stack as the page is not being created again) &lt;/li&gt;    &lt;li&gt;Page Loaded event fired &lt;/li&gt;    &lt;li&gt;Page Unloaded event fired (when you navigate away from the page) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Now that we understand the page life cycle events how do we determine how the page is being build?&lt;/p&gt;  &lt;p&gt;1) Create an enumeration which helps us understand the life stage of the page&lt;/p&gt;  &lt;pre class="c-sharp" name="code"&gt;/// 
/// Enumeration to provide details on the view stage for a given view.
/// This is used to determine if a view is being newly constructed or if it has been
///     pulled off of the backstack
/// 
public enum ViewLifeStage
{
    /// 
    /// Will indicate that the view has been newly created.
    /// This will be set when the view has been navigated to via forward navigation
    /// 
    Constructed,        

    /// 
    /// Will indicate that the view has been reloaded off of the backstack
    /// This will be set when the view is navigated to via the back button/back stack
    /// 
    Rehydrated          
}&lt;/pre&gt;

&lt;p&gt;2) Set the initial&amp;#160; life stage in the constructor of the page (remember this is ONLY hit on forward navigation)&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;ViewsLifeStage = ViewLifeStage.Constructed;&lt;/pre&gt;

&lt;p&gt;3) Update the life stage when you unload the page&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;ViewsLifeStage = ViewLifeStage.Rehydrated;&lt;/pre&gt;

&lt;p&gt;4) Check the life stage when you load a page (if needed)&lt;/p&gt;

&lt;pre class="c-sharp" name="code"&gt;if ( ViewsLifeStage == ViewLifeStage.Rehydrated )
{
    // do something here
}&lt;/pre&gt;

&lt;p&gt;As you can see from the steps above there is a few lines of code you need to create, but nothing too much.&amp;#160; Again the above appears to work, but it may not be as elegant (oh and I am not sure I like the terms used in the enumeration, but that is a simply terminology change).&amp;#160; If there is a better/cleaner solution for this please let me know.&lt;/p&gt;

&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=63693" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/WP7/default.aspx">WP7</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/WindowsPhone/default.aspx">WindowsPhone</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Silverlight/default.aspx">Silverlight</category></item><item><title>My Silverlight Breakpoints are not being hit….How To Resolve this</title><link>http://devlicio.us/blogs/derik_whittaker/archive/2010/06/25/my-silverlight-breakpoints-are-not-being-hit-how-to-resolve-this.aspx</link><pubDate>Fri, 25 Jun 2010 08:35:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:60734</guid><dc:creator>Derik Whittaker</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/rsscomments.aspx?PostID=60734</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devlicio.us/blogs/derik_whittaker/commentapi.aspx?PostID=60734</wfw:comment><comments>http://devlicio.us/blogs/derik_whittaker/archive/2010/06/25/my-silverlight-breakpoints-are-not-being-hit-how-to-resolve-this.aspx#comments</comments><description>&lt;p&gt;Today I was working on a Silverlight 4 side application and for some odd reason my breakpoints were not being hit when I was debugging.&amp;nbsp; I took what I thought were the right steps to resolve the issue.&amp;nbsp; I &amp;hellip;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Killed the development web service&lt;/li&gt;
&lt;li&gt;Killed and restarted Firefox (3.6.4)&lt;/li&gt;
&lt;li&gt;Killed and restarted VS 2010&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Sadly none of these options worked&amp;hellip;&amp;hellip;hum&lt;/p&gt;
&lt;p&gt;Next I hit up google for an answer.&amp;nbsp; My blogger in crime Chris Bennage has a similar &lt;a href="http://devlicio.us/blogs/christopher_bennage/archive/2010/01/17/silverlight-breakpoints-not-being-hit.aspx"&gt;post here&lt;/a&gt; that I read through, and tried.&amp;nbsp; However, this did not resolve my issue.&amp;nbsp; However when reading through the comments someone said something that sparked a thought.&amp;nbsp; That was to attach the debugger to the browser.&amp;nbsp; So I tried this, however that also did not work, but I was on the right track.&lt;/p&gt;
&lt;p&gt;In order for ME (and please note you may have a different end result than I did here) was to do the following.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Start the project without debugging so it would open up in the browser&lt;/li&gt;
&lt;li&gt;Open up the Attach to Process dialog in VS     &lt;br /&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_2A9858CE.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_2BCCCBE0.png" width="364" border="0" height="247" /&gt;&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;Change the &amp;lsquo;Attach to&amp;rsquo; options and explicitly check Silverlight (this option may not be needed, but hey it worked)     &lt;br /&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_145217AF.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_408E9E93.png" width="364" border="0" height="196" /&gt;&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;Scroll down in the Process dialog until you find something that has the type set to &amp;lsquo;Silverlight&amp;rsquo;, If it says &amp;#39;plugin-container.exe&amp;rsquo; then you are on the right one (this is what the silverlight plugin runs in when running Firefox).     &lt;br /&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_499B2A14.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" alt="image" src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/derik_5F00_whittaker/image_5F00_thumb_5F00_78BCEFDE.png" width="484" border="0" height="328" /&gt;&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;Click Attach&lt;/li&gt;
&lt;li&gt;Debug away&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Now again, this worked for me, this may NOT work for you.&amp;nbsp; Also, there may be a better way to do this, but this works until I can find the root cause.&lt;/p&gt;
&lt;p&gt;Till next time,&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=60734" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/HowTo/default.aspx">HowTo</category><category domain="http://devlicio.us/blogs/derik_whittaker/archive/tags/Silverlight/default.aspx">Silverlight</category></item></channel></rss>