2009-09-17 29 views
9

all. Ben sadece sayısal girişlere izin veren bir usercontrol "NumericTextBox" var. Bir başka özel davranış sergilemeliyim, yani bir VM değerine OneWayToSource bağlayabilmek için ihtiyacım var ve sadece metin kutusuna odaklanırken enter tuşuna bastığımda VM değeri güncellemesine sahip olmalıyım. Anahtarya bastığımda çıkan EnterPressed olayına zaten sahibim, sadece bu eylemi bağlamanın güncellenmesine neden olacak bir yol bulmaktan çok zorlanıyorum ...Yalnızca girerken bağlanmayı güncelleyen WPF metin kutusu

cevap

11

Ciltleme ifadenizde, UpdateSourceTrigger öğesini ayarlayın. Açıkça EnterPressed olayını işlerken

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

Daha sonra, bu, gerçek bağlı özelliğine metin değeri itecek, bağlama ifadesi üzerindeki UpdateSource arayın. Eğer MVVM kullanıyorsanız

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

ne zaman metin PreviewKeyUp üzerinde UpdateSource çağıran özel ekli özelliği ile birlikte decastelijau yaklaşımının bir arada kullanabilirsiniz.

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

Sonra yapabilirsiniz:

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); 
    } 
: Burada
<TextBox myprops:UpdaterProps.UpdateSourceOnKey="Enter" ... /> 
7

Anderson İmes tarafından sağlanan fikrinin tam sürümüdür