Home > OS >  C# - WPF/MVVM - Unable to set property value from view
C# - WPF/MVVM - Unable to set property value from view

Time:04-28

I'm opening a dialog in my view in response to a button click. I have a file class with the filePath property like so:

FileClass.cs

    private string _filePath;

    public string FilePath
    {
        get { return _filePath; }
        set 
        { 
            _filePath = value;
            OnPropertyChanged();
        }
    }

I create an instance in my viewModel:

viewmodel

    public MyFile myFile;
    public ViewModel()
    {
        myFile = new MyFile();
    }

The problem is when I try to use the property in the view:

            if (openFileDialog.ShowDialog() == true)
            {
                filePath = openFileDialog.FileName;

                (this.DataContext as ViewModel)?.myFile.FilePath = filePath; // error

            }

Why can't I do this?

CodePudding user response:

If you read the error it'll tell you that (this.DataContext as ViewModel)?.myFile.FilePath isn't an l-value. It's also non-sense.

Use this instead:

((ViewModel)DataContext).myFile.FilePath = filePath;

Of course, your setup breaks both MVVM guidelines and .Net naming and field conventions, but to each his own.

  • Related