0
votes

In C#/UWP, How to get a two-way binding to update the field on every key-click in a textbox,rather than once at the end of typing by unfocus the Textbox control after filling it out? Here are the details:

I have a textbox that is bound to a class string variable.

<StackPanel Name="MyStackPanel Margin="10">
    <TextBox Header="MyTextBox:Item1" 
          Text="{Binding MyField, Mode=TwoWay}"/>
    <Button Name="MyButton" Content="Next" Click="Next_Item"/>
</StackPanel>

public class MyItem {
    public string MyField {get;set;}
}

public class MyPage : Page {
    MyItem MyItem1 = new MyItem();
    MyItem MyItem2 = new MyItem();

    public MyPage() {
        MyStackPanel.DataSource = MyItem1;
    }

    bool toggle = false;
    public MyButton_Click( ... ) {
        if (!toggle) { 
            MyStackPanel.DataSource = MyItem2;
            MyTextBox.Header = "MyTextBox:Item2";
            toggle = true;
        } 
        else {    
            MyStackPanel.DataSource = MyItem1;
            MyTextBox.Header = "MyTextBox:Item1";
            toggle = false;
        }        
    }

The problem i'm having is that when i fill out MyTextBox, and then click MyButton without unfocusing the MyTextBox Control, in this case the Two-Way binding doesn't work to copy the Text of MyTextBox back to the binding object MyItem1.MyField. However, binding works if I type something into MyTextBox, then unfocus the MyTextBox control, and then click Button.

Any Items on how to fix this problem?

1

1 Answers

2
votes

If you want the source to be updated as you type, set the UpdateSourceTrigger of the binding to PropertyChanged.

Check this micosoft doc