views:

1320

answers:

2

Hi,

In WPF, I would like to be able to template how my bindings are applied by default.

For instance, I want to write :

Text="{Binding Path=PedigreeName}"

But it would be as if I had typed :

Text="{Binding Path=PedigreeName, Mode=TwoWay, UpdateSourceTrigger=LostFocus, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"

Any idea ?

Thanks,

  • Patrick
+10  A: 

Use one of the overloads of DependencyProperty.Register that take a PropertyMetadata. Pass an instance of FrameworkPropertyMetadata and set its properties.

public class Dog {
    public static readonly DependencyProperty PedigreeNameProperty =
        DependencyProperty.Register("PedigreeName", typeof(string), typeof(Dog),
            new FrameworkPropertyMetadata() {
                BindsTwoWayByDefault = true,
                DefaultUpdateSourceTrigger = UpdateSourceTrigger.LostFocus
            }
        );

I don't offhand see a way to set the defaults for NotifyOnValidationError, ValidatesOnDataErrors, or ValidatesOnExceptions, but I haven't used this enough to be sure what to look for; they may be there.

Joe White
Thanks, nice idea, but in my case, the Dog class is in a business model project. I don't want to add a dependency on System.Windows for this project. The solution I was looking fo was in that direction, something like putting <Style TargetType="{x:Type Binding}"> <Setter Property="Mode" Value="TwoWay" /> ... <Setter Property="ValidatesOnDataErrors" Value="True" /> <Setter Property="ValidatesOnExceptions" Value="True" /> </Style>In the App.xaml, but have not found anything matching... Thanks again !
PBelanger
+8  A: 

In addition to Joe White's good answer, you could also create a class that inherits from Binding and sets the default property values you need. For instance :

public class TwoWayBinding : Binding
{
    public TwoWayBinding()
    {
        Initialize();
    }

    public TwoWayBinding(string path)
      : base(path)
    {
        Initialize();
    }

    private void Initialize()
    {
        this.Mode = BindingMode.TwoWay;
    }
}
Thomas Levesque
Thanks, I ended up implementing it that way.[code] public class ValidationBinding : Binding { public ValidationBinding() { Initialize(); } public ValidationBinding(string path) : base(path) { Initialize(); } private void Initialize() { Mode = BindingMode.TwoWay; UpdateSourceTrigger = UpdateSourceTrigger.LostFocus; NotifyOnValidationError = true; ValidatesOnDataErrors = true; ValidatesOnExceptions = true; } }[/code]
PBelanger
Does this also work in Silverlight 3+ ?
Lars Udengaard