Click here to Skip to main content
15,919,879 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Am browsing the file by openfiledialog and need to get the path in textbox so after writing the code like

private void Browse()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = "*.";
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.";

if (ofd.ShowDialog() == true)
{
string filename = ofd.FileName;
}
}
am having the path in "string filename" which i want to bind with the textbox,please any one can help me to get bind with the textbox

What I have tried:

am not getting to get the variable value into property so i can bind directly to textbox or if any solution have please help.
Posted
Updated 6-Dec-19 2:54am
v2

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:
C#
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:
C#
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);
    }
}
 
Share this answer
 
Comments
Member 14654140 11-Dec-19 6:00am    
Yes Dear it is working thank you so much . . . !
Try:
MyTextBox.Text = filename;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900