pátek 18. března 2016

C# Caliburn.Micro Check Unmatched Elements

Caliburn.Micro is a great C# MVVM framework. It saves the developer's fingers with the binding by the x:Name convention:
<textbox x:name="Username" />
However, when one mistypes the x:Name or rename the property in the ViewModel then the Caliburn silently does not apply the binding. Such mistakes are hard to track. Fortunately Caliburn comes with the help of ViewModelBinder.HandleUnmatchedElements. We have a simple rule in the project: if the x:Name starts with the capital letter, then it has to be binded by the Caliburn. Then I have been able to plug in a simple method to check for unmathched elements starting with the capital:
ViewModelBinder.HandleUnmatchedElements = (elems, type) =>
    if (!elems.Any())

    // elems with Name with the first letter upper case
    elems = elems.Where(e => !string.IsNullOrEmpty(e.Name) && e.Name.StartsWith(e.Name.Substring(0, 1).ToUpperInvariant()));
    if (!elems.Any())

    throw new InvalidOperationException(type + " contains Caliburn unmatched elements " + string.Join(",", elems.Select(e => e.Name)));

Žádné komentáře: