Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply UpdateSourceTrigger=PropertyChanged to all textboxes wpf

Tags:

c#

.net

wpf

How can I write template look like this?

    <DataTemplate ... TextBlock>
    UpdateSourceTrigger=PropertyChanged
    </DataTemplate>
like image 594
syned Avatar asked Feb 10 '12 11:02

syned


2 Answers

You cannot change the default mode for the UpdateSourceTrigger in a style. This is configured as the DefaultUpdateSourceTrigger of the FrameworkPropertyMetadata class when the DependencyProperty (in this case the Text property) is registered.

You could either create a custom text box type which derives from TextBox and changes this value when registering the dependency property. Alternatively, you might want to look into the Caliburn.Micro MVVM framework, which automatically sets this for all text boxes in an app (via code, as part of its convention based binding).

like image 140
devdigital Avatar answered Oct 17 '22 03:10

devdigital


Just extending accepted answer (and yes, i know i am necromancing this question :) ):

Actually, own TextBox is pretty simple, lets call it TextBoxExt (not much extended, but you know...)

public class TextBoxExt : TextBox
{
    private static readonly MethodInfo onTextPropertyChangedMethod 
      = typeof(TextBox).GetMethod("OnTextPropertyChanged", BindingFlags.Static | BindingFlags.NonPublic);
    private static readonly MethodInfo coerceTextMethod 
      = typeof(TextBox).GetMethod("CoerceText", BindingFlags.Static | BindingFlags.NonPublic);
    static TextBoxExt()
    {
      
      TextProperty.OverrideMetadata(
        typeof(TextBoxExt),

        // found this metadata with reflector:
        new FrameworkPropertyMetadata(string.Empty,
                                      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal,
                                      new PropertyChangedCallback(MyOnTextPropertyChanged),
                                      new CoerceValueCallback(MyCoerceText),
                                      true, // IsAnimationProhibited
                                      UpdateSourceTrigger.PropertyChanged)
        );
    }

    private static object MyCoerceText(DependencyObject d, object basevalue)
    {
      return coerceTextMethod.Invoke(null, new object[] { d, basevalue });
    }

    private static void MyOnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      onTextPropertyChangedMethod.Invoke(null, new object[] { d, e });
    }

  }

and somewhere in your {ResourceDictionary}.xaml or in App.xaml:

<Style TargetType="{x:Type control:TextBoxExt}"
       BasedOn="{StaticResource {x:Type TextBox}}" />
like image 28
Jan 'splite' K. Avatar answered Oct 17 '22 05:10

Jan 'splite' K.