Category Archives: Binding

Nice MultiValueConverter

If you have a MultiBinding and you want to get true when every binding evaluates to the same value, then this is four you, little pollo:

 public class AllEqualConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (!values.Any())
            {
                return true;
            }

            var first = values.First();

            var allAreTheSame = values.All(other => Equals(first, other));
            return allAreTheSame;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("This is only mean to support conversions in One Way");
        }
    }
Advertisements

Don’t leave my this way!

UPDATE. My Glass library contains an improved version of this behavior. Take a look at it!

Aha! So you just discovered that users tend to break your applications typing everything you could imagine. Validation in Hell!

Imagine you have some information that has to be filled in. For example, this Window tell you to enter a value between 1 and 5.image

It may be not obvious to the user that information is extremely important. So you cannot leave it in an invalid state.

Boy, those mandatory fields must be valid before you go away!

But, how do you keep they into the TextBox? The user types “2000” and suddenly, they change the focus to the Dummy text box.

The required TextBox will show its value is invalid, but maybe the user is happy with that red TextBox and starts to touching here and there with something that is wrong. This can be, of course, perfectly acceptable, but sometimes the information you request just cannot be left in an invalid state.

That is why I made this Interaction Behavior. KeepFocusOnErrorBehavior.

If you attach it to any TextBoxBase (like TextBox), you will notice it will not let you change the focus to another control while it doesn’t pass the validation. Example:


As you can see, this behavior is attached to the TextBox and its ErrorCommand is set to a Command (in a View Model). This command makes it even better, because you can, for example, bind a Command that shows a message indicating that you’re not allowed to go anywhere before entering correct input.

I hope you like it Sonrisa

Here is the code:

public class KeepFocusOnErrorBehavior : Behavior<TextBoxBase> {
        protected override void OnAttached() {

            AssociatedObject.PreviewLostKeyboardFocus += AssociatedObjectOnPreviewLostKeyboardFocus;
            base.OnAttached();

        }

        private void AssociatedObjectOnPreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs keyboardFocusChangedEventArgs) {

            var textBindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);

            // Forces to update the binding. As we are preventing the focus to be lost, its binding never updates and never recovers from a previous error.
            textBindingExpression.UpdateSource();

            var value = Validation.GetHasError(AssociatedObject);
            if (value) {
                keyboardFocusChangedEventArgs.Handled = true;
                ExecuteErrorCommandIfCanExecute();
            }
        }

        private void ExecuteErrorCommandIfCanExecute() {
            if (ErrorCommand != null) {
                if (ErrorCommand.CanExecute(ErrorCommandParameter))
                    ErrorCommand.Execute(ErrorCommandParameter);
            }
        }

        #region ShowErrorMessageCommand
        public static readonly DependencyProperty ErrorCommandProperty =
          DependencyProperty.Register("ErrorCommand", typeof(ICommand), typeof(KeepFocusOnErrorBehavior),
            new FrameworkPropertyMetadata((ICommand)null));

        public ICommand ErrorCommand {
            get { return (ICommand)GetValue(ErrorCommandProperty); }
            set { SetValue(ErrorCommandProperty, value); }
        }

        #endregion

        #region ErrorCommandParameter
        public static readonly DependencyProperty ErrorCommandParameterProperty =
          DependencyProperty.Register("ErrorCommandParameter", typeof(object), typeof(KeepFocusOnErrorBehavior),
            new FrameworkPropertyMetadata((object)null));

        public object ErrorCommandParameter {
            get { return (object)GetValue(ErrorCommandParameterProperty); }
            set { SetValue(ErrorCommandParameterProperty, value); }
        }

        #endregion

    }

SelectedItem, SelectedValue

Los ComboBox, las ListBox y toda esa recua de controles tan útiles son unas verdaderas bestias. En realidad, todos los ItemsControl son tan bellos como complejos.

No entender qué cojopios hacen es una de las razones por la que creamos chorricode totalmente vomitivo. “ItemsControl”, quédate con el nombre. ¡Hay que estudiárselos bien!

A nivel de usuario hay básico entender este par de propiedades:

  • SelectedItem: El elemento seleccionado. Si tenemos un Binding TwoWay a esta propiedad debemos cuidar muy mucho ciertas cosas. Lo más importante:

    El elemento enlazado con el “binding” puede no existir en la lista. Si esto se produce, visualmente no se seleccionará NADA. Es decir, ningún elemento se marcará.

  • SelectedValue: Valor seleccionado. No importa si el elemento no está en la lista. Se selecciona y punto. Queda más claro si digo que en un combo box, el Popup desplegable lleva la lista de elementos, pero luego tiene un elemento especial, que es el que aparece en la cajita del combo cuando está cerrado. El SelectedValue se pondrá ahí. Lo malo es que no siempre es posible representar el elemento (puede ser un elemento no “renderizable”.

IMPORTANTE: Para que la cosa funcione es imprescindible sobreescribir los métodos Equals en los elementos que vayan a ser representados en el ItemsControl. Es lógico, puesto que, ¿cómo va a saber sino cuál elemento se selecciona de la lista si no existe una manera de comprobar cuándo son el mismo elemento?

WARNING: El método Equals por defecto compara referencias, por lo que si son la misma referencia, el SelectedItem furrula fairly good, pero cuando la instancia te la sacas tú de la manga, haces un clone y vete tú a saber qué historias, el Equals es obligatorio si quieres que todo se sincronice solito.

¡Esos Equals tan impopulares a los que nadie les hace caso son importantísimos! Úsalos o tendré que sacar el látigo de dar.

Databinding to Structs

Well, this is going to be rude: Binding to struct types can be a tricky. You will absolutely love when the UI just ignores every change. It refuses to update and eventually you’ll get mad about this, wondering why those nice bindings to Paddings or Margins are ignored. It’s kind of frustrating.

This boils down the nature of structs. They are value types and they’re taken as a whole by the dependency property mechanism.

When you define a DP that carries a struct, any binding to a child attribute that composes that struct reflects the actual value of that member, but ONLY when the struct is replaced by another “instance” of the struct (another value). Changing its attributes will not notify any change (Property Changed callbacks won’t be called).

For instance, you have a DP with a Point and a binding link this:

Text=”{Binding Path=MyPoint.X}”

Suppose that the X value of the struct is modified the some other binding (or whatever). You may expect the Text to reflect the X value anytime it is changed, but no way! WPF will blow you off, sticking out its long and complex tongue.

This is (not easily) solved replacing the value of the struct whenever you want the change to be reflected in the UI. “What? you mean that I have to care about changes in every member of the struct in order to have the bindings fresh like my cotton underwear”. Yes, that’s it!

Pretty annoying! but this is the price you have to pay for using those cute simplistic and handy structs!

Don’t forget it. Never! You sweated too much because of this Sonrisa! I hope you finally understood, Suppa JMN!

Y todo esto para tirarme el pegote de escribir en Inglés, ¡copón! Bueno, también es verdad que si algún lobo de mar angloparlante viene a mi blog por alguna casualidad de la vida, quizá le guste entender algo, ¿no?