0

I have a text bound to a property as follows

The user is expected to type in a File Name. Sometimes however users may type in invalid characters. So my backing property in the View Model looks as shown below

private string outputFileName;
public string OutputFileName
    {
        get 
        {
            return outputFileName;
        }
        set 
        {
            string temp = value;
            if (true == IsValidFileName(temp))// this function uses Path.Getinvalidfilechars
            {
                outputFileName = value;

            }
            else
            {
                MessageBox.Show(string.Format("{0} contains one or more invalid characters  
                for a file Name",temp));
            }
            base.OnPropertyChanged("OutputFileName");
        }
    }

Here is the problem, the text box still shows the invalid char. why is the OnPropertyChanged not causing the text in the text box to go back to the old value without the invalid char. How can I get that behaviour

H.B.
  • 166,899
  • 29
  • 327
  • 400
Rahul
  • 2,194
  • 4
  • 31
  • 46

2 Answers2

0

What is the base class of your class that defines the OutputFileName? That class' OnPropertyChange method seems to check if the property value really changed before firing the PropertyChanged event. I tried your example with a class that directly implements INotifyPropertyChanged and does

if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs("OutputFileName"));
}

and that works as you expect. Although i agree with Marc, showing a MessageBox from a property setter is rather uncommon.

Clemens
  • 123,504
  • 12
  • 155
  • 268
0

In the else statement, the backing field for OutputFileName is not being assigned a different value. If you want to revert back to the previous value, then save that in another variable and update the backing field in the else statement and then the property changed event will change the UI with the old value. Although, I don't think this is very good user experience.

A better solution would to be use some validators and inform the user that the input needs to be corrected, rather than just reverting the value back to the previous value.

Google up "wpf validation" or start with this SO question: WPF Data Binding and Validation Rules Best Practices

Community
  • 1
  • 1
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • that's exactly what he wants: not setting the backing field but - in the TextBox - reverting to the current value of the property, i.e. the unchanged field value. As i wrote, that works if he invokes INotifyPropertyChanged.PropertyChanged directly. – Clemens Jan 15 '12 at 21:53