For MVVM to work, you need to use a property. The property setter needs to raise a
PropertyChanged
event.
Assuming you have a sensible base class:
private string _fileName;
public string FileName
{
get { return _fileName; }
set { SetProperty(ref _fileName, value); }
}
private void Browse()
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.DefaultExt = ".txt";
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.";
if (ofd.ShowDialog() == true)
{
FileName = ofd.FileName;
}
}
}
Bind your
TextBox
to the
FileName
property on your view-model.
Example base class:
public abstract class ViewModelBase : INotifyPropertyChanged
{
private static readonly ConcurrentDictionary<string, PropertyChangedEventArgs> EventArgsCache = new ConcurrentDictionary<string, PropertyChangedEventArgs>();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler is null) return;
PropertyChangedEventArgs e = EventArgsCache.GetOrAdd(propertyName, n => new PropertyChangedEventArgs(n));
handler(this, e);
}
protected void SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(storage, value)) return;
storage = value;
OnPropertyChanged(propertyName);
}
}