2011-11-24 36 views
0

我試圖捕獲在文本框上按下的Enter鍵,以便我可以開始更新到服務器。這不起作用,所以我將問題簡化爲簡單元素。如何使綁定發生從ViewModel

在這個例子中,看起來綁定並不是按鍵擊發生的,而是在稍後的某個時間。我需要在輸入鍵被按下時完成綁定。考慮VM中的以下XAML和功能。

這裏的文本框

<TextBox Text="{Binding TextValue, Mode=TwoWay}" Height="23" Width="300"> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="KeyDown"> 
      <cmd:EventToCommand Command="{Binding KeyDownCommand}" 
       PassEventArgsToCommand="True" /> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
</TextBox> 

的KeyDownCommand火的XAML不如預期,howerver價值尚未在TextValue財產。如果我再次點擊輸入,那麼價值是在財產?這是KeyDownCommand。 ViewModel的構造函數正確設置keyDownCommand。

public RelayCommand<RoutedEventArgs> KeyDownCommand { get; private set; } 
private void KeyDownAction(RoutedEventArgs eventArg) 
{ 
    var source = eventArg.OriginalSource as FrameworkElement; 
    var e = eventArg as KeyEventArgs; 
    if (source != null && e != null && e.Key== Key.Enter) 
    { 
     e.Handled = true; 
     MessageBox.Show(TextValue); 
    } 
} 

看來,我需要的是「後」的文本框的文本回VM的TextValue財產時,按下回車鍵的方式。或者是有什麼我失蹤了。

回答

2

試穿結合,這樣的設置UpdateSourceTriggerPropertyChanged

<TextBox Text="{Binding TextValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="23" Width="300"> 

現在視圖模型屬性將被更新每個文本改變時。

更新:

的Silverlight,作爲替代UpdateSourceTrigger,你可以用下面的簡單行爲的更新綁定源每當文本的變化:

public class TextChangedUpdateSourceBehavior : Behavior<TextBox> 
{ 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 

     AssociatedObject.TextChanged += OnTextChanged; 
    } 

    private void OnTextChanged(object sender, TextChangedEventArgs e) 
    { 
     var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty); 

     if (bindingExpression != null) 
     { 
      bindingExpression.UpdateSource(); 
     } 
    } 
} 

使用方法如下:

<TextBox Text="{Binding TextValue, Mode=TwoWay}" Height="23" Width="300"> 
    <i:Interaction.Behaviors> 
     <b:TextChangedUpdateSourceBehavior /> 
    </i:Interaction.Behaviors> 
</TextBox> 
+0

事實證明UpdateSouceTrigger = PropertyChanged不是Silverlight的選項。唯一的兩個選項是Default和Explicit。 –

+0

@Ralph - 對不起,沒有注意到這個問題是針對Silverlight的。查看我的Silverlight解決方案的更新答案。 –

1

我剛剛發佈了這個問題,而不是找到答案。

這裏的修正KeyDownAction

private void KeyDownAction(RoutedEventArgs eventArg) 
{ 
    var source = eventArg.OriginalSource as FrameworkElement; 
    source.GetBindingExpression(TextBox.TextProperty).UpdateSource(); 
    var e = eventArg as KeyEventArgs; 
    if (source != null && e != null && e.Key== Key.Enter) 
    { 
     e.Handled = true; 
     MessageBox.Show(TextValue); 
    } 
} 

中,現在我在多達現在我的視圖模型知道更多關於認爲,它應鍵入此我意識到我「破」的格局。