2012-02-10 32 views

回答

10

您不能在樣式中更改UpdateSourceTrigger的默認模式。當DependencyProperty(在此例中爲Text屬性)註冊時,這被配置爲FrameworkPropertyMetadata類的DefaultUpdateSourceTrigger

您可以創建自TextBox派生的自定義文本框類型,並在註冊依賴項屬性時更改此值。或者,您可能需要查看Caliburn.Micro MVVM框架,它會自動爲應用程序中的所有文本框(通過代碼,作爲其基於約定的綁定的一部分)設置此框架。

+0

我已經更新了答案。 – devdigital 2012-02-10 11:51:55

+0

你有沒有看過使用MVVM框架?它可以爲您節省大量的工作,而Caliburn.Micro則是一種樂趣。如果您想推出自己的解決方案,那麼可能會編寫自定義標記擴展或自定義綁定,而不是創建自己的TextBox派生類型。看看http://www.paulstovell.com/wpf-delaybinding或http://www.hardcodet.net/2008/04/wpf-custom-binding-class有些想法。 – devdigital 2012-02-10 12:11:15

+0

謝謝你的回答! – syned 2012-02-10 12:15:23

1

只是延長接受的答案(是的,我知道我necromancing這個問題:)):

其實,自己的文本框是非常簡單的,讓我們把它叫做TextBoxExt(沒有多少擴展的,但你知道... )

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),callback 
             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 }); 
    } 

    } 

,並在您{} ResourceDictionary中或名爲.xaml在App.xaml中的某處:

<Style TargetType="{x:Type control:TextBoxExt}" 
     BasedOn="{StaticResource {x:Type TextBox}}" /> 
相關問題