双向绑定(bind)效果很好,但在 TextBox 的情况下,它会在控件失去焦点时发生。
就我而言,我有一个简单的 UI,带有 1 个文本框和提交/取消按钮。
提交按钮在 View 上设置为默认值。因此,用户可以在文本框中输入文本并点击“Enter”,这将调用提交的命令。这很好,但我需要从 TextBox 访问值,它不在 VM 中,因为 TextBox 没有失去焦点。如何强制从我的代码更新此 binging?
<TextBox
Text="{Binding Comment, Mode=TwoWay}"
Grid.Row="2"/>
<StackPanel
Grid.Row="3"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Padding="20,5"
Margin="5"
Command="{Binding CancelCommand}"
Content="Cancel" IsCancel="True" />
<Button
Padding="20,5"
Margin="5"
Command="{Binding SubmitCommand}"
Content="Submit" IsDefault="True" />
</StackPanel>
最佳答案
在 TextBox 绑定(bind)上使用 UpdateSourceTrigger=PropertyChanged。
关于.net - 以编程方式强制 TextBox 值从 V 到 VM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165471/