2010-03-30 21 views
7

我正在創建一個數字文本框WPF,有兩個按鈕來增加和減少值。如何強制WPF文​​本框上的TextChanged事件並保持焦點?

我創建了兩個的RoutedCommand管理behiavor和它們運作良好。我只想解決一個問題。我希望控件在執行增加或減少命令時通知綁定到其TextProperty的所有對象。

在它發出的通知的那一刻,只有當我將焦點移到另一個控件

任何幫助非常感謝, 謝謝

回答

11

使用UpdateSourceTrigger="Explicit"在結合和TextChanged事件更新BindingSource。 所以你寫的東西是這樣的:

<NumericTextBox x:Name="control" Text={Binding Path=MyProperty}/> 

,而不是做這樣的

<NumericTextBox x:Name="control" Text={Binding Path=MyProperty, UpdateSourceTrigger=Explicit}/> 

TextChanged事件處理程序更新綁定。

control.GetBindingExpression(NumericTextBox.TextProperty).UpdateSource(); 

並且完成了。 希望它有幫助!

+0

@viky非常感謝!我忘了這是可能的使用表達式「control.GetBindingExpression(NumericTextBox.TextProperty).UpdateSource();」那是完美的。我只在用戶按下增加和減少按鈕時調用它,並在手動更改文本時使用正常行爲。 – Drake 2010-03-31 09:13:32

+7

爲什麼不簡單地使用'Text =「{Binding YourBindableProperty,UpdateSourceTrigger = PropertyChanged}」'? – 2013-01-23 10:13:33

2

TextBox上Text屬性綁定的默認行爲是在LostFocus上更新。您可以在靜態構造函數重載的TextProperty元數據在您的自定義控件更改此:

static NumericTextBox() 
{ 
    TextProperty.OverrideMetadata(
     typeof(NumericTextBox), 
     new FrameworkPropertyMetadata("", // default value 
      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
      null, // property change callback 
      null, // coercion callback 
      true, // prohibits animation 
      UpdateSourceTrigger.PropertyChanged)); 
} 
+0

@ abe謝謝安倍,非常有用但viky的回答對我的情況更加靈活 – Drake 2010-03-31 09:14:33

25

有一個簡單的方法:

Text="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}" 

(我測試的文本框)。 好運

+1

+1。 'Text =「{綁定MyTextProperty,UpdateSourceTrigger = PropertyChanged}」似乎是最好的方法。 – 2011-04-09 01:31:54

相關問題