Search code examples
.netwpfxamldata-bindingmvvm

Force TextBox value from V to VM programmatically?


Two-way binding works excellent, but in case of TextBox it happens when control loses focus.

In my case I have simple UI with 1 TextBox and Submit/Cancel buttons.

Submit button set as Default on a view. So, user can type text into textbox and hit "Enter" which will invoke Submit's command. This is good, but I need to access value from TextBox and it's not in VM because TextBox didn't loose focus. How do I force this binging to update from my code?

<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>

Solution

  • Use UpdateSourceTrigger=PropertyChanged on your TextBox binding.