MVVM and me – Part 2

I could have done this post yesterday but that would have been a long essay. Today we are going to look at displaying static data on XAML pages.

In C# when you have data that does not change, one tends to use const or static readonly. const causes compiler to replace all occurrences of variable usage with the actual data at compile time. That means you assemblies has no lookups at run-time. Static read-only is a static variable that can also be set in constructor – is read-only otherwise.

Now based on my previous experience doing WinForms and Webforms, normally I tend to set those directly in XAML. Say you want to content of a button or a textblock text (label). So the ideal way would be.

  1. Take View Model
  2. Define consts
  3. Set bindings to consts
  4. Compile and reload

Eureka.. there’s nothing..

Well XAML bindings make a big fuss of INotifyPropertyChanged interface. From sample I know that it works with properties so could it be that ?

Lets start:

  1. Take View Model
  2. Define consts
  3. Define properties
  4. Set property in the constructor to consts
  5. Set bindings to properties
  6. Compile and reload

There.. much better..

Lesson, const and compiler time optimisations are no good.. you need to define properties and additionally call PropertyChanged events and what not including set the properties at VM Creation in order to display data the proper MVVM way. A Single task of setting a text to a textblock or a button is translated into a handful tasks..

Update 1:
My friend @Scottisafool … suggested an alternative approach that he tends to use

  1. Define resources in App.xaml
  2. Set bindings to resources
  3. Compile and reload

This also works.. sure it means that all your strings are in one place but that’s still not MVVM
So it turns out there is not right way but there is a wrong way!! Everything else but code-behind as the last resource is the pukka MVVM way. Wrap up for today I think.

Update 2:
More messages suggesting that the mechanism to declare labels is to either hard code those or use Resources. That’s all fine.. I could use ResourceDictionary just in case the future me might want to localise the app.

That however still leaves the need to support of real consts impossible. There isn’t any support for those in bindings wrt View Model

Advertisement

HexColor for use with #wpdev and #win8dev

I found this code a while back and its been very handy at times. I have no idea where I found it so I apologise for not attributing it to the writer. Hope this is helpful to others as it has been to me.

public struct HexColour
{
    // Regex: This pattern matches hex codes in these two formats:
    // #000000 (no alpha value) and #FF000000 (alpha value at front).
    const string HEX_PATTERN = @"^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{8})$";

    const int LENGTH_WITH_ALPHA = 8;

    Color _color;

    public HexColour(string hexCode)
    {
        if (hexCode == null)
        {
            throw new ArgumentNullException("hexCode");
        }

        if (!Regex.IsMatch(hexCode, HEX_PATTERN))
        {
            throw new ArgumentException("Format must be #000000 or #FF000000 (no extra whitespace)", "hexCode");
        }

        // shave off '#' symbol
        hexCode = hexCode.TrimStart('#');

        // if no alpha value specified, assume no transparency (0xFF)
        if (hexCode.Length != LENGTH_WITH_ALPHA)
            hexCode = String.Format("FF{0}", hexCode);

        _color = new Color();
        _color.A = byte.Parse(hexCode.Substring(0, 2), NumberStyles.AllowHexSpecifier);
        if (_color.A < 50)
            _color.A = 50;
        _color.R = byte.Parse(hexCode.Substring(2, 2), NumberStyles.AllowHexSpecifier);
        _color.G = byte.Parse(hexCode.Substring(4, 2), NumberStyles.AllowHexSpecifier);
        _color.B = byte.Parse(hexCode.Substring(6, 2), NumberStyles.AllowHexSpecifier);
    }

    public byte A
    {
        get { return _color.A; }
        set { _color.A = value; }
    }

    public byte R
    {
        get { return _color.R; }
        set { _color.R = value; }
    }

    public byte G
    {
        get { return _color.G; }
        set { _color.G = value; }
    }

    public byte B
    {
        get { return _color.B; }
        set { _color.B = value; }
    }

    // Implicit cast from HexColor to Color
    public static implicit operator Color(HexColour hexColor)
    {
        return hexColor._color;
    }

    // Implicit cast from Color to HexColor
    public static implicit operator HexColour(Color color)
    {
        HexColour c = new HexColour();
        c._color = color;
        return c;
    }

    // Just like with Color, ToString() prints out the hex value of the
    // color in #ARGB format (example: #FF000000) by default.
    public override string ToString()
    {
        return ToString(true);
    }

    // I don't always need the alpha value, so I added an overload here
    // that lets me return the hex value in #RBG format (example: #000000).
    public string ToString(bool includeAlpha)
    {
        if (includeAlpha)
        {
            return _color.ToString();
        }
        else
        {
            return String.Format("#{0}{1}{2}", _color.R.ToString("x2"), _color.G.ToString("x2"), _color.B.ToString("x2"));
        }
    }
}

Happy coding

Slydr 3.0 submitted for testing

I finally finished all localisation in all Mango supported languages except korean and japanese as Slydr doesn’t support them. I also completed the marketplace description etc which also had to be translated.

Well its all in now. Thinking about it. I think in only missed out on one thing – disable check for user added words when user dictionaries are chinese. I need to start using a ToDo list.

It has been a long 2 months now.. doing word lists / custom dictionaries / code changes etc. I am just glad its working

Resource String Translator

For a while now i am having to constantly check and double check translations of various strings that are using in various WP7 apps.

Until Mango WP7 apps supported 5 languages and localization involved creating resource files for all entries for those languages max. Now with Mango, WP7 supports about 19 languages and maintaining / building resource files translating each bit can be challenging.

Well help is at hand.. Introducing the “Resource String Translator”.

What does it do ? Well you enter your text in English and the app translates it to other languages. Infact it goes a step further and does a reverse translation to see whether translation is accurate or not. It usually gives you a fair idea. You can download it from my company website ResStringTranslator.zip

If you find it useful, i want to know about it.

Slydr Progress Update

Slydr rework is close to completion. Now slydr uses entire trace to determine match. There is no speed detection.

You can trace fast or slow and you will get same result.. unlike before. I have also consumed a new algorithm which genenrates a probability / similarity between 0 and 1. The algorithm executes after Levenstein Distance and is slower so i had to resort to changes to reduce number of items i match and it seems to work fine now. Might continue optimising it to remove unncessary work later.

As a result, i had to redo all dictionaries to ensure that in addition to word, i also had path data depending upon that language / layout. Its has taken me a long time as the code i used to generate new dictionaries was WPF but i tried to stay as close to Silverlight as i could.

On UI side, i have moved entire code to using TouchScreen TouchReported event unlike before where part of work was done in TouchReported and other was done using high level Mouse Enter event.

Instead of spawning new threads to check for new user added words, i have moved to using threadpool.

I have to test a few bits like migrating existing user added words to generate trace path and i am going to add persistance of user usage. In addition i need to add ability to reset user added words and usage from settings page.

I am sure there will still be complains but what can i do ?

Reworking Slydr Dictionaries

In Slydr (See FAQ for more info) i consume the word lists that i have made available publicly.
Currently in Slydr, based on user trace, i generate a cleaned char list which is then use to find probable matches. This solution works in mosts cases as it uses user hesitation to determine the correct character.

While this works in mosts cases, there are always those who complain that it is too damn slow.
well there are things I can do and i am doing those. From next version of Slydr, there will be no char filteration, if you enter abcdefghi that is exactly what is used to char matching algorithm.

What i cannot do is make word matching faster. Unsafe code is a strict NO and i dont think i can speed up raw word matching.

I am hoping to reuse the logic i used to modify word lists. It is currently based on c# and WPF but i have kept it as close to Slydr code which is in WP7 Silverlight as possible. This way i can allow same optimsation for user word addition.