2009-09-17 11 views
9

all. Ho un controllo utente "NumericTextBox" che consente solo voci numeriche. Ho bisogno di esibire un altro comportamento specializzato, cioè, ho bisogno che sia in grado di associarlo a un valore VM OneWayToSource e di avere l'aggiornamento del valore VM solo quando premo invio mentre si concentra la casella di testo. Ho già un evento EnterPressed che si attiva quando premo il tasto, sto solo facendo fatica a trovare un modo per fare in modo che l'azione aggiorni l'associazione ...Casella di testo WPF che aggiorna solo il binding quando viene premuto Invio

risposta

11

Nell'espressione di associazione, impostare UpdateSourceTrigger in modo esplicito.

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

Poi, quando la gestione dell'evento EnterPressed, chiamano UpdateSource sull'espressione vincolante, questo spingerà il valore dalla casella di testo alla proprietà bound effettivo.

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

Se si sta utilizzando MVVM è possibile utilizzare una combinazione di approccio di decastelijau insieme ad una proprietà personalizzata collegata che chiama UpdateSource sulla casella di testo quando PreviewKeyUp.

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

allora si può fare:

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

Ecco una versione completa dell'idea fornito da Anderson Imes:

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); 
    } 
Problemi correlati