Search code examples
c#wpfxamldata-bindingwpf-style

Set Binding property in Style in XAML C#


I'm searching for a way to set the binding property UpdateSourceTrigger in a Style. Currently I'm setting it on every TextBox manually like this:

<TextBox Text="{Binding boundValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

What I want to do is something like this (But this obviously doesn't work):

<Window.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Binding.UpdateSourceTrigger" Value="PropertyChanged" />
    </Style>
</Window.Resources>
<Grid>
    <TextBox Text="{Binding boundValue, Mode=TwoWay}"/>
</Grid>

Solution

  • Styles are meant for FrameworkElements (and derivated controls).

    Binding is not a FrameworkElement.

    Anyway you can create your own markup extension for setting Binding's properties that your need:

    public class PropertyChangedBinding : Binding
    {
        public PropertyChangedBinding(string path)
            : base(path)
        {
            UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
        }
    
        public PropertyChangedBinding()
            : base()
        {
            UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
        }
    }
    

    So in your XAML you can use {local:PropertyChangedBinding ...}.