如何将 TextBox 文本与 ViewModel 正确绑定 属性
How do I properly bind TextBox Text with ViewModel Property
我的视图中有一个文本框:
<TextBox x:Name="FilePath" Grid.Column="1" Height="30" Text="{Binding FilePath}"/>
在视图模型中,我正在更改浏览按钮命令的路径:
RelayCommand _browseButtonCommand;
public ICommand BrowseButtonCommand
{
get
{
if (_browseButtonCommand == null)
{
_browseButtonCommand = new RelayCommand(param =>
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if ((openFileDialog.ShowDialog() == true))
{
FilePath = openFileDialog.FileName;
}
});
}
return _browseButtonCommand;
}
}
string _filePath;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; OnPropertyChanged("_filePath"); }
}
但为什么更新后的路径值没有出现在我的文本框中?在我 select 来自对话框的文件后,我能够看到值正在变化!!
您需要使用 public 属性 的名称通知 OnPropertyChanged,而不是私有字段的名称。
set { _filePath = value; OnPropertyChanged("FilePath"); }
我的视图中有一个文本框:
<TextBox x:Name="FilePath" Grid.Column="1" Height="30" Text="{Binding FilePath}"/>
在视图模型中,我正在更改浏览按钮命令的路径:
RelayCommand _browseButtonCommand;
public ICommand BrowseButtonCommand
{
get
{
if (_browseButtonCommand == null)
{
_browseButtonCommand = new RelayCommand(param =>
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if ((openFileDialog.ShowDialog() == true))
{
FilePath = openFileDialog.FileName;
}
});
}
return _browseButtonCommand;
}
}
string _filePath;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; OnPropertyChanged("_filePath"); }
}
但为什么更新后的路径值没有出现在我的文本框中?在我 select 来自对话框的文件后,我能够看到值正在变化!!
您需要使用 public 属性 的名称通知 OnPropertyChanged,而不是私有字段的名称。
set { _filePath = value; OnPropertyChanged("FilePath"); }