我正在我的視圖中打開一個對話框以回應按鈕單擊。我有一個帶有 filePath 屬性的檔案類,如下所示:
檔案類.cs
private string _filePath;
public string FilePath
{
get { return _filePath; }
set
{
_filePath = value;
OnPropertyChanged();
}
}
我在我的 viewModel 中創建了一個實體:
視圖模型
public MyFile myFile;
public ViewModel()
{
myFile = new MyFile();
}
問題是當我嘗試在視圖中使用該屬性時:
if (openFileDialog.ShowDialog() == true)
{
filePath = openFileDialog.FileName;
(this.DataContext as ViewModel)?.myFile.FilePath = filePath; // error
}
為什么我不能這樣做?
uj5u.com熱心網友回復:
如果您閱讀錯誤,它會告訴您這(this.DataContext as ViewModel)?.myFile.FilePath不是左值。這也是無稽之談。
改用這個:
((ViewModel)DataContext).myFile.FilePath = filePath;
當然,您的設定違反了 MVVM 指南和 .Net 命名和欄位約定,但對每個人來說都是他自己的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466477.html
