How to setup a ViewModel binding for a TextBox wit

2019-06-05 08:08发布

For some reason I can't get my textbox/property binding to work "automatically" with Reactive UI.

My DataContext is setup like this:

My ViewModel is setup in the code behind for the MainWindow.xaml.cs:

public MainWindowViewModel ViewModel { get; protected set; }

public MainWindow()
{
    ViewModel = new MainWindowViewModel();
}

In my WPF MainWindow.xaml I have the DataContext and the have a textbox element like this:

(Other properties ommitted)

<Window x:Name="Window">
    <Grid DataContext="{Binding ViewModel, ElementName=Window}">
        <StackPanel x:Name="ContentGrid" Grid.Row="1">
            <TextBox Name="Password" Text="{Binding Password, Mode=TwoWay}" />
            ...

In the MainWindowViewModel I have a property and field like this:

string _PasswordConfirmation;

public string PasswordConfirmation
{
    get { return _PasswordConfirmation; }
    set { this.RaiseAndSetIfChanged(x => x.PasswordConfirmation, value); }
}

I also have a command that is setup like this:

var canHitOk = this.WhenAny(
    x => x.Password,
    x => x.PasswordConfirmation,
    (pass, confirm) => (pass.Value == confirm.Value && pass.Value.Length > 3));

OkCommand = new ReactiveCommand(canHitOk);

As you can guess, I also have the password confirmation textbox/property setup too, and the command set for a button (The password confirmation TextBox has the same problem). Since the field/property combos are never updated in the ViewModel, the button is never enabled.

I debugged and confirmed that the ViewModel is bound to the XAML, but the text never gets updated in the field/property combos when typing in the TextBoxes.

I looked at the sample WP7 application in the GitHub repo and they manually bind the KeyUp event to set the text in the text in the property/field. If I follow this convention, I have this in my MainWindow.xaml:

Password.KeyUp += (o, e) =>
{
    ViewModel.Password = Password.Text;
};

But is that the right way to do it? I thought Reactive UI would handle the binding as I've seen in other MVVM frameworks, unless I'm mistaken. Is there an easier way?

UPDATE

As Paul Betts pointed out in the comments in his answer, you can enable the binding to automatically update by adding this property to the binding:

UpdateSourceTrigger=PropertyChanged

which would make the TextBox element look like this:

<TextBox Name="Password" Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}" />

1条回答
我只想做你的唯一
2楼-- · 2019-06-05 08:33

The problem is that WP7 TextBox doesn't Update its binding automatically on KeyUp - this is a problem with every MVVM framework sadly.

查看更多
登录 后发表回答