2009-09-17 11 views
9

all。私は数値コントロールのみを許可する "NumericTextBox"というユーザーコントロールを持っています。私はそれをVM値OneWayToSourceにバインドすることができ、テキストボックスにフォーカスを合わせながらEnterキーを押すとVM値の更新のみができるようにするために、別の特殊な動作を行う必要があります。私はすでにキーを押したときに起きるEnterPressedイベントを持っていますが、バインドを更新するためにそのアクションを引き起こす方法を考え出すのは苦労しています...入力時にバインディングのみを更新するWPFテキストボックス

答えて

11

バインディング式で、UpdateSourceTrigger明示的にEnterPressedイベントを処理するとき

Text="{Binding ..., UpdateSourceTrigger=Explicit}" 

そして、これは実際のバウンドプロパティにテキストボックスから値をプッシュしますが、バインディング式にUpdateSourceを呼び出します。あなたはMVVMを使用している場合

BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty); 
exp.UpdateSource(); 
3

あなたはテキストボックスPreviewKeyUpにUpdateSourceを呼び出して、カスタム添付プロパティと一緒にdecastelijauのアプローチを組み合わせて使用​​することができます。

public static readonly DependencyProperty UpdateSourceOnKey = DependencyProperty.RegisterAttached(
    "UpdateSourceOnKey", 
    typeof(Key), 
    typeof(TextBox), 
    new FrameworkPropertyMetadata(false) 
); 
public static void SetUpdateSourceOnKey(UIElement element, Key value) 
{ 

    //TODO: wire up specified key down event handler here 
    element.SetValue(UpdateSourceOnKey, value); 

} 
public static Boolean GetUpdateSourceOnKey(UIElement element) 
{ 
    return (Key)element.GetValue(UpdateSourceOnKey); 
} 

次に、あなたが行うことができます:ここでは

<TextBox myprops:UpdaterProps.UpdateSourceOnKey="Enter" ... /> 
7

はアンダーソンのIMEが提供するアイデアの完全なバージョンです:

public static readonly DependencyProperty UpdateSourceOnKeyProperty = 
    DependencyProperty.RegisterAttached("UpdateSourceOnKey", 
    typeof(Key), typeof(TextBox), new FrameworkPropertyMetadata(Key.None)); 

    public static void SetUpdateSourceOnKey(UIElement element, Key value) { 
     element.PreviewKeyUp += TextBoxKeyUp; 
     element.SetValue(UpdateSourceOnKeyProperty, value); 
    } 

    static void TextBoxKeyUp(object sender, KeyEventArgs e) { 

     var textBox = sender as TextBox; 
     if (textBox == null) return; 

     var propertyValue = (Key)textBox.GetValue(UpdateSourceOnKeyProperty); 
     if (e.Key != propertyValue) return; 

     var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty); 
     if (bindingExpression != null) bindingExpression.UpdateSource(); 
    } 

    public static Key GetUpdateSourceOnKey(UIElement element) { 
     return (Key)element.GetValue(UpdateSourceOnKeyProperty); 
    } 
関連する問題