“Hacking” through Prism regions (or when to cross the lines with Prism)

19 ביולי 2011

11 comments

If you’ve been following this blog long enough, you should know I’m an avid prism fan. Most of my projects I am making use of Prism or Composite Application Guidance. This is not a post for learning Prism, but to provide a solution, not so straight-forward for a rather straight-forward problem.

I must add that that rarely I had had been pushed to extreme solutions such as I show you here. For most scenarios you are pretty much good with the default behaviors.

In my scenario I’ve been using a control as a region. This control requires that when adding views to it, it must be done with RegisterViewWithRegion extension method. The concept is simple in contrast to the “regular” AddToRegion method. RegisterViewWithRegion doesn’t requires the region to be initialized, yet. When the region becomes available than those views who had been registered will be called via delegates and added to the now ready region.

A regular usage of RegisterViewWithRegion is as follows:

public void AddView(object view)
{
    RegionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => view);
}

A common scenario is to allow clients to "readd” a view, but instead of duplicating it, just put into focus, or in Prism concepts, activate the view. This is were things get messy. For an example let’s simplify it a bit and for the following wrong code snippet let’s just do nothing when the view already exist.

public void AddView(object view)
{
    if (!RegionManager.Regions[RegionNames.MainRegion].Views.Contains(view))
    {
        RegionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => view);
    }
}

Why is this code bad? if have a reason to use RegisterViewWithRegion, most likely it fail to check if the view exist if the region is not ready yet. So we need to move this check into the action delegate, to be called only when the region is ready.

public void AddView(object view)
   {

       RegionManager.RegisterViewWithRegion(RegionNames.MainRegion, 
           () =>
           {
             if (!RegionManager.Regions[RegionNames.MainRegion].Views.Contains(view))
             {
                 return view;
             }
             return null;
           });
   }

Last code looks formidable but there is a catch, when we returning null, it is actually adding a null view to the region. In my scenario it’s really an undesired side effect of the whole situation. It is worth mentioning that a RegionAdapter doesn’t solve this issue completely, when you react to a view being added you can decide to not do  anything but than the underlying control is out of sync with the views collection as the views collection will keep those nulls as views. While it might serve for some purposes, I haven’t thought it is clean enough. Also it kept me checking for nulls every time I iterate over the region views.

So luckily, the prism source code is open for grab, though I wanted to avoid altering the source code by all means, I’ve followed the key players involved when you register a view with RegisterViewWithRegion.

To make a long story short one need to dwell into Region Behaviors, in specific responsible for the scenario above is the AutoPopulateRegionBehavior. Soon enough I could identify the culprit:

public virtual void OnViewRegistered(object sender, ViewRegisteredEventArgs e)
       {
           if (e == null) throw new System.ArgumentNullException("e");

           if (e.RegionName == this.Region.Name)
           {
               AddViewIntoRegion(e.GetView());
           }
       }

When we call e.GetView() it will call our delegate, if GetView returns null than it will add a null, no brainer. Fortunately the Prism team did a good job, and provided us a mean to change those behaviors on many levels, by making this virtual I could’ve created my own version of AutoPopulateRegionBehavior that avoided adding nulls. I inherited from it and overridden this method.

Last piece of the puzzle is the making the configuration  of the behavior factory to use my version instead of the one coming from the box. This is done actually rather easily by overriding the bootstrapper ConfigureDefaultRegionBehaviors method.

What I ended up doing but didn’t like so much is copy pasting the original implementation of ConfigureDefaultRegionBehaviors  and changing it to use my own AutoPopulateRegionBehavior because the Factory didn’t give me a way to replace an existing behavior. Perhaps the Prism team can make this available in the next version.

Ariel

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

11 comments

  1. Thorn14 באוגוסט 2012 ב 3:26

    Gigzon – Hire Freelancers from $1 to $100. Looking for gigs?

    Make money from home by providing small business services. Deliver
    your gig and earn money online.

    Reply
  2. Hay17 באוקטובר 2012 ב 3:40

    KOROX – office market, s.r.o. je dodávateľ kompletného spotrebného materiálu pre vašu kanceláriu ale taktiež širokého tovaru
    pre domácnosť . Špecializujeme sa hlavne na kancelárske potreby
    . spotrebný materiál doručíme ku vám už do 24 hodín po celom území Slovenska.

    KOROX – office market, s.r.o. je dodávateľ kompletného sortimentu
    pc pre vašu kanceláriu ale taktiež širokého sortimentu
    pre spoločnosť; . Špecializujeme sa hlavne na fotoaparáty
    . kancelársky nábytok doručíme ku vám už do 24 hodín po celom území Slovenska.

    Najväčšie obchodné internetové centrum v SR – korox.

    sk prevádzkuje spoločnosť; KOROX – office market, s.r.o.

    Na stránkach http://www.korox.sk môžete nájsť širokú ponuku
    a najlacnejšie mobilné telefóny , reklamné predmety , mobilných telefónov, papiernictvo
    , mobilné telefóny produktov. Ide o sortiment zahrňujúci
    viac ako 1 000 svetových značiek. Hlavnou prednosťou
    http://www.korox.sk je však rozsiahla ponuka pridaných služieb.

    Prečo nakupovať; na http://www.korox.sk? Sme jednotka na
    slovenskom trhu v reklamné predmety . Široký sortiment –
    1 000 svetových značiek a 80 tisíc položiek tovaru.
    Veľké skladové zásoby – rýchle doručenie tovaru zákazníkom.
    Poskytujeme rozsiahly systém rozšírených záruk / dokúpenie dlhšej záruky / až
    30 dní na vrátenie tovaru / expresné vybavenie reklamácií v prvých 30 dňoch od nákupu.
    Výhodné ceny tovaru. Najväčšia kamenná predajňa
    v Banskej Bystrici na osobný odber tovaru. Možnosť vrátenia tovaru / odstúpenia od zmluvy aj pre právnické osoby.

    Reply
  3. Eaton17 באוקטובר 2012 ב 7:32

    Velky vyber hraciak na eshope Perinbaba.sk v kategorii Hracky, ale aj Dojcenske hracky, Hracky pre dievcata, Hracky pre chlapcov,
    Hracky pre chlapcov.

    Reply
  4. Murdock17 באוקטובר 2012 ב 10:59

    Fotografie na objednavku, svadobny fotograf, reportazna fotografia.
    Profesionalny fotograf, fotograf pre fotografovanie spolocenskych akcii.

    Reply
  5. Musselman18 באוקטובר 2012 ב 2:08

    Reklamna agentura. Lider v digitalnej reklame s vyuzitim multimedialnych aplikacii.
    Vyroba reklamy a navrh reklamnych spotov. ACTION MEDIA
    INTERNATIONAL.

    Reply
  6. Cockrell18 באוקטובר 2012 ב 3:27

    Etikety – Etikety univerzalne farebne, Etikety na
    DVD, Etikety tabelacne … za najlacnejsie ceny. Tovar
    skladom s dorucenim do 24 hod. pre cele Slovensko.

    Reply
  7. Tinsley18 באוקטובר 2012 ב 11:24

    digitalne fotoaparaty , fotoaparaty – digitalne fotoaparaty , fotoaparaty Canon, Nikon, Sony,
    Olympus… za najlepsie ceny. Tovar skladom,
    lacno a s dorucenim do 24 hod. Nakupujte online.

    Reply
  8. Stamper18 באוקטובר 2012 ב 14:35

    Velky vyber tovaru na eshope http://www.korox.sk v kategorii playstation hry
    , ps3 , napriklad PS3 – The Godfather 2, PS3 – Resistance 2 – PLATINUM, PS3 – Carnival Island.

    Reply
  9. http://www.retailuggboots.net25 באוקטובר 2012 ב 20:52

    Hey there all people, proceed to hear as well as post about grooveshark. net, you feel totally liable once they actually head to judge over the top of it.

    Reply
  10. Goff11 בנובמבר 2012 ב 0:42

    Postove obalky – Postove obalky samolepiace, Bublinkove obalky,
    Obalky kartonove na diskety a CD, Bezpecnostne obalky, Postove obalky
    s okienkom … za najlacnejsie ceny. Tovar skladom s dorucenim do 24 hod.

    pre cele Slovensko.

    Reply
  11. Lujan1 בספטמבר 2013 ב 17:00

    What sophisticated products do we have today for hair removal.
    With advances in statistical regression analysis, it
    should become feasible that lawyers today can optimize courtroom performance with the help of proficient mathematicians.
    The ability to choose how much paint to use proves to be a benefit
    for most people.

    Reply