2014-02-19 34 views
0

我從TextBox-KeyUp事件對ViewModel執行命令。我遇到的問題是,在執行命令時,TextBox中綁定到ViewModel上的屬性的文本(仍然)爲空。從代碼隱藏執行命令時未設置MVVM模型屬性

視圖模型:

private string _myText; 
public string MyText 
{ 
    get { return _myText; } 
    set 
    { 
     _myText = value; 
     RaisePropertyChanged("MyText"); 
    } 
} 

// ... ICommand stuff here 

private object HandleMyCommand(object param) 
{ 
    Console.WriteLine(MyText); // at this point MyText --> 'old' value, e.g. null 
    return null; 
}} 

XAML:

<StackPannel> 
    <TextBox x:Name="tbTest" KeyUp="TextBox_KeyUp" Text="{Binding MyText, Mode=TwoWay}" /> 
    <Button x:Name="btnTest" Content="Click" Command="{Binding MyCommand}" /> 
</StackPannel> 

後面的代碼:

private void TextBox_KeyUp(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Enter) 
    { 
     if (btnTest.Command.CanExecute(null)) 
     { 
      btnTest.Command.Execute(null); 
     } 
    } 
} 

結合和命令都工作。以正常方式執行命令時,使用按鈕,該屬性設置得很好。

我沒有正確地做到這一點?

回答

2

設置UpdateSourceTrigger=PropertyChanged因爲默認情況下MyText將在失去重心被更新:

Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 

也,不相關的問題,但你可以爲TextBox創建InputBinding執行一些Command輸入按:

<TextBox x:Name="tbTest" Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
    <TextBox.InputBindings> 
     <KeyBinding Key="Enter" Command="{Binding MyCommand}"/> 
    </TextBox.InputBindings> 
</TextBox> 
+1

我真的很喜歡InputBinding的建議。使用MVVM我寧願不執行代碼隱藏的commandexecution。 –

0

嘗試將文本屬性的綁定更改爲:

Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
相關問題