c# - WPF MVVM 绑定从 ViewModel 工作到 XAML,但不是相反。我究竟做错了什么?
问题描述
所以这是我的 XAML:
<TextBox Name="FirstNameTextBox"
Text="{Binding Mode=TwoWay, Path=FirstName}"
Style="{StaticResource StandardTextBoxTheme}"
Width="180"
HorizontalAlignment="Left"
Margin="0 0 0 10" />
<Button Name="CreatePersoenlicheUntersuchungButton"
Content="Unterlagen erstellen"
Style="{StaticResource StandardButtonTheme}"
Command="{Binding CreateMedicalExaminationCommand}"
HorizontalAlignment="Left" />
这是我的 ViewModel:
public class MedicalExaminationViewModel : INotifyPropertyChanged
{
private IGlobalConfig _globalConfig;
private ILogger _logger;
private IDataAccess _dataAccess;
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged(this, () => FirstName);
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
OnPropertyChanged(this, () => LastName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ICommand CreateMedicalExaminationCommand { get; set; }
public MedicalExaminationViewModel(ILogger logger, IDataAccess dataAccess, IGlobalConfig globalConfig)
{
_globalConfig = globalConfig;
_logger = logger;
_dataAccess = dataAccess;
CreateMedicalExaminationCommand =
new RelayCommand(new Action<object>(CreateMedicalExaminationAsync));
}
// This method gets called when pressing the Button and the Text in the Textboxes gets updated after setting the Properties here.
public async void CreateMedicalExaminationAsync(object obj)
{
FirstName = "Test_FirstName";
LastName = "Test_LastName";
System.Windows.Forms.MessageBox.Show(FirstName);
System.Windows.Forms.MessageBox.Show(LastName);
}
public virtual void OnPropertyChanged<T>(object source, Expression<Func<T>> propertyExpression)
{
string propertyName = GetPropertyName(source, propertyExpression);
if (PropertyChanged != null)
{
PropertyChanged(source, new PropertyChangedEventArgs(propertyName));
}
}
public string GetPropertyName<T>(object source, Expression<Func<T>> propertyExpression)
{
var memberExpression = propertyExpression.Body as MemberExpression;
var propertyName = memberExpression.Member.Name;
return propertyName;
}
}
当我填写 TextBox 并按下按钮时,CreateMedicalExaminationAsync() 会被调用。但是 FirstName 属性为空。当我在 ViewModel 中设置 FirstName 属性时,它会在视图中按应有的方式更新。如何将 TextBox.Text 放入 ViewModel 中的属性中?提前致谢!
编辑:删除 Yarik 提到的样式使其立即生效。非常感谢。
解决方案
推荐阅读
- javascript - 如何在平板设备上获取经度和纬度?JS 地图框
- xml - 将带有嵌套节点的 xml 导入 Access(并且需要使用 xsl 将 xml 转换为“平面”结构)
- c# - 基于sqlite本地数据库的单个属性绑定
- key - 如何排除 Parse-Server REST API 上的默认键
- angular - 角度路线:子路线已加载但未渲染
- r - 将 dplyr group_by/summarize/spread 变成一个函数
- python - 克罗内克乘法仅适用于特定轴
- angular - 找不到 API 编译器 cli、函数 VERSION 错误:找不到 API 编译器 cli、函数 VERSION
- android - 致命异常:java.lang.UnsatisfiedLinkError centrifuge-android
- node.js - 如何将 XLSX 添加到服务器端 Node JS