Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caliburn Micro: how to set binding UpdateSourceTrigger?

I've been exploring the Caliburn Micro MVVM Framework just to get a feel for it, but I've run into a bit of a problem. I have a TextBox bound to a string property on my ViewModel and I would like the property to be updated when the TextBox loses focus.

Normally I would achieve this by setting the UpdateSourceTrigger to LostFocus on the binding, but I don't see any way to do this within Caliburn, as it has setup the property binding for me automatically. Currently the property is updated every time the content of the TextBox changes.

My code is very simple, for instance here is my VM:

public class ShellViewModel : PropertyChangeBase
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set 
        { 
            _name = value; 
            NotifyOfPropertyChange(() => Name);
        }
    }
}

And inside my view I have a simple TextBox.

<TextBox x:Name="Name" />

How to I change it so the Name property is only updated when the TextBox loses focus, instead of each time the property changes?

like image 951
Alex McBride Avatar asked Feb 17 '11 18:02

Alex McBride


1 Answers

Just set the binding explictly for that instance of the TextBox and Caliburn.Micro won't touch it:

<TextBox Text="{Binding Name, UpdateSourceTrigger=LostFocus}" />

Alternatively, if you want to change the default behaviour for all instances of TextBox, then you can change the implementation of ConventionManager.ApplyUpdateSourceTrigger in your bootstrapper's Configure method.

Something like:

protected override void Configure()
{
  ConventionManager.ApplyUpdateSourceTrigger = (bindableProperty, element, binding) =>{
#if SILVERLIGHT
            ApplySilverlightTriggers(
              element, 
              bindableProperty, 
              x => x.GetBindingExpression(bindableProperty),
              info,
              binding
            );
#else
            if (element is TextBox)
            {
                return;
            }

            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
#endif
  };
}
like image 109
devdigital Avatar answered Oct 22 '22 18:10

devdigital