Jan Kratochvil
Jan Kratochvil

Reputation: 2327

Binding source not updating

A follow the MVVM pattern. I need the TextBox to trigger a property setter on the viewModel every time the Text in the TextBox changes. The problem is that the setter on ViewModel is never called. This is what I've got:

View (.cs)

public partial class AddShowView : PhoneApplicationPage
{
    public AddShowView()
    {
        InitializeComponent();
    }

    private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
    {
        DataContext = new AddShowViewModel(this.NavigationService);
    }

    private void SearchTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
    {
        var textBox = (TextBox)sender;
        var binding = textBox.GetBindingExpression(TextBox.TextProperty);
        binding.UpdateSource();
    }
}

View (.xaml), only the relevant part

<TextBox Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="{Binding SearchText, UpdateSourceTrigger=Explicit}" TextChanged="SearchTextBox_TextChanged_1" />

ViewModel

public class AddShowViewModel : PageViewModel
{
    #region Commands

    public RelayCommand SearchCommand { get; private set; }

    #endregion

    #region Public Properties

    private string searchText = string.Empty;
    public string SearchText
    {
        get { return searchText; }
        set
        {
            searchText = value;
            SearchCommand.RaiseCanExecuteChanged();
        }
    }

    #endregion

    public AddShowViewModel(NavigationService navigation) : base(navigation)
    {
        SearchCommand = new RelayCommand(() => MessageBox.Show("Clicked!"), () => !string.IsNullOrEmpty(SearchText));
    }
}

The binding from source to target works, I've double checked, so the DataContext is set correctly. I have no idea where I went wrong. Thanks for helping out.

Upvotes: 1

Views: 908

Answers (1)

Claus J&#248;rgensen
Claus J&#248;rgensen

Reputation: 26347

You need to set the binding mode to be TwoWay, otherwise it'll only read the value from your ViewModel, not update it.

Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=Explicit}"

Upvotes: 1

Related Questions