Search code examples
xamlmvvmmvvm-light

Bound string value from ViewModel not updating in UI element


I have this TextBlock in XAML that its text property is bound to a viewmodel command.

<TextBlock Text="{Binding SomeText}"></TextBlock>

Meanwhile, the viewmodel looks like this:

\\ the text property
private string _someText = "";

public const string SomeTextPropertyName = "SomeText";
public string SomeText
{
    get
    {
        return _someText;
    }
    set
    {
        Set(SomeTextPropertyName, ref _someText, value);
    }
}

\\ the command that changes the string

private RelayCommand<string> _theCommand;

public RelayCommand<string> TheCommand
{
    get
    {
        return _theCommand
            ?? (_theCommand = new RelayCommand<string>(ExecuteTheCommand));
    }
}

private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \\ MessageBox.Show(SomeText);
}

I can successfully call the TheCommand as I did able to call a MessageBox using that command from the triggering element. The SomeText value also change as shown in the commented MessageBox line. What am I doing wrong here, is there any silly mistake?


Solution

  • You're setting the field _someText directly, which means you're by-passing the setter of the SomeText property. But that setter is calling the Set(SomeTextPropertyName, ref _someText, value); method that is internally raising the PropertyChanged event.

    That PropertyChanged event is necessary for the Data Binding, so that it knows the SomeText property was updated.

    That means, instead of doing this:

    private void ExecuteTheCommand(string somestring)
    {
        _someText = "Please Change";
        \\ MessageBox.Show(SomeText);
    }
    

    Just do this and it should work:

    private void ExecuteTheCommand(string somestring)
    {
        SomeText = "Please Change";
        \\ MessageBox.Show(SomeText);
    }