Search code examples
wpfupdatesourcetrigger

Wpf: The text block doesn't update after change


I have Wpf application that uses MVVM and the code looks as following:

XAML:

<StackPanel Orientation="Vertical">
    <TextBox Text="{Binding DataFolder}" TextWrapping="Wrap"/>
    <Button Content="Convert" Padding="8" Command="{Binding ConvertCommand}" IsEnabled="True" MinWidth="220"/>
    <TextBlock Text="{Binding DoneMessage, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
</StackPanel>

ViewModel:

public class ConverterViewModel : NotificationObject
{
    public string DataFolder { get; set; }
    public string DoneMessage { get; set; }
    public DelegateCommand ConvertCommand { get; set; }

    private readonly List<BaseConverter> _converters = new List<BaseConverter>
    {
        new VisualCheckEventConverter()
    };

    public ConverterViewModel()
    {
        ConvertCommand = new DelegateCommand(VisualCheckEventConvertCommandExecute);
        DataFolder = ConfigurationManager.AppSettings["InputFolder"];
        DoneMessage = "Not done yet.";
    }

    private void VisualCheckEventConvertCommandExecute()
    {
        foreach (var c in _converters)
            c.Convert(DataFolder);
        DoneMessage = "Done!";
    }
}

When I run the application, the message "Not done yet." is displayed, but after the command is executed the text block's text is not updated to "Done!".

How to make it work?


Solution

  • You need to notifypropertychanged in your DoneMessage property setter if you want the view to be notified.
    Also, AFAIK there's no sense in putting UpdateSourceTrigger=PropertyChanged on your TextBlock since it's read only. You should place it on your TextBox if you want your ViewModel to be notified when text is changed.
    Should be something like this:

        private string _doneMessage;
    
        public string DoneMessage
        {
            get { return _doneMessage; }
            set
            {
                _doneMessage = value;
                //the method name may vary based on the implementation of INotifyPropertyChanged
                NotifyPropertyChanged("DoneMessage");
            }
        }