Style for bindings?

I have text fields in a user control:

<TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"></TextBox> <TextBox Text="{Binding Path=Street, UpdateSourceTrigger=PropertyChanged}"></TextBox> 

Is there a way in XAML to do something like a style for my bindings, so that I do not need to write UpdateSourceTrigger=PropertyChanged for each text field, but only a part of Path= ?

Thank you in advance!

+4
source share
2 answers

No, there is no way to do this using XAML or style. The best you can hope for is to create a custom control that will change the default behavior. Sort of:

 public class MyTextBox : TextBox { static MyTextBox() { TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata() { DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); } } 

Then you need to use MyTextBox instead of TextBox .

+2
source

It also became very unpleasant for me to write some crazy long binding EVERY time when I wanted to get attached to a property, so I did it for more than a year before I came across this post.

These are basically subclasses of MarkupExtension (which is the Binding class) for an abstract class named BindingDecoratorBase provides all the properties that the Binding class provides. So from there you can do something like this:

 public class SimpleBinding : BindingDecoratorBase { public SimpleBinding(string path) : this() { Path = new System.Windows.PropertyPath(path); } public SimpleBinding() { TargetNullValue = string.Empty; UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; } } 

And then all you need to do in your xaml is include your namespace at the top, and then to bind to the control, do something like this:

 <TextBox Text="{m:SimpleBinding Name}"></TextBox> <TextBox Text="{m:SimpleBinding Street}"></TextBox> 

This will make it easier than trying to subclass each individual control that you want to write less in the anchor phrase.

+5
source

All Articles