【问题标题】:KeyBinding (Enter) on textbox doesn't update model文本框上的 KeyBinding (Enter) 不会更新模型
【发布时间】:2014-07-12 10:57:21
【问题描述】:

当我在文本框中按回车键时,我尝试执行命令 AddTodoCommand:

<TextBox x:Name="TbTodo" Text="{Binding TodoTask.Text, Mode=TwoWay}" >
      <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding AddTodoCommand}" />
      </TextBox.InputBindings>
</TextBox>

方法执行正确,但属性 TodoTask.Text 为空。

当我用这个命令模型点击按钮时有值:

<Button x:Name="BtnAdd" Command="{Binding AddTodoCommand}" Content="Button" 

我认为在按下按钮之前文本框会更改焦点并更新绑定。

进入后如何更新模型?

【问题讨论】:

    标签: wpf xaml mvvm-light


    【解决方案1】:

    TextBox.Text 的默认 UpdateSourceTrigger 是 LostFocus。这就是为什么您在 TodoTask.Text 中看不到“新”值的原因。解决此问题的一种方法是将 UpdateSourceTrigger 更改为 PropertyChanged

    【讨论】:

      【解决方案2】:

      您可以删除文本框 InputBindings,并将您的 Button xaml 更改为使用 IsDefault 属性,如下所示,Enter 将适用于此按钮的任何文本框,并且将调用 AddTodoCommand

      <Button x:Name="BtnAdd" IsDefault="true" Command="{Binding AddTodoCommand}" Content="Button"/> 
      

      【讨论】:

      • 这行不通。当我按回车然后执行命令但值为空(相同的效果)
      • 但是您使用 IsDefault="true" 的解决方案比 KeyBinding 更好:)
      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 2017-03-18
      • 2020-06-13
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      相关资源
      最近更新 更多