我的ViewModel
public class MyViewModel : ViewModelBase
{
// INotifyPropertyChanged is implemented in ViewModelBase
private String _propX;
public String PropX
{
get { return _propX; }
set
{
if (_propX != value)
{
_propX = value;
RaisePropertyChanged(() => PropX);
}
}
}
private String _propY;
public String ServerIP
{
get { return _propY; }
set
{
if (_propY != value)
{
_propY = value;
RaisePropertyChanged(() => ServerIP);
}
}
}
public A()
{
this._propY = "000.000.000.000";
this._propY = "000.000.000.000";
}
}
// EDIT
// This is the command that resets the properties
private RelayCommand _resetFormCommand;
public ICommand ResetConnectionFormCommand
{
get
{
if (_resetFormCommand == null)
{
_resetFormCommand = new RelayCommand(param => this.ExecuteResetFormCommand(), param => this.CanExecuteResetFormCommand);
}
return _resetFormCommand;
}
}
private bool CanExecuteResetFormCommand
{
get
{
return !String.IsNullOrWhiteSpace(this._propX) ||
!String.IsNullOrWhiteSpace(this._propY);
}
}
private void ExecuteResetFormCommand()
{
this._propX = "";
this._propY = "";
}
我的观点xaml
<TextBox Name="propX" Text="{Binding PropX }" PreviewTextInput="textBox_PreviewTextInput" />
<TextBox Name="propY" Text="{Binding PropY }" PreviewTextInput="textBox_PreviewTextInput" />
<Border>
<Button Content="Reset" Name="resetBtn" Command="{Binding ResetFormCommand}" />
</Border>
我的View代码背后
private MyViewModel vm;
public ConnectionUserControl()
{
InitializeComponent();
vm = new MyViewModel();
this.DataContext = vm;
}
private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
ValidateInput(sender as TextBox, e);
}
reset命令重置我的视图模型中的属性,但文本框仍然包含它们的值,绑定不能正常工作:(我在这里遗漏了什么?
5 回答
您应该重置属性,而不是私有成员:
private void ExecuteResetFormCommand()
你是如何重置这些值的?重置值时,您可能会覆盖数据绑定 . 如果您发布单击按钮时执行的代码,将会很有帮助 .
在您的xaml代码中,您必须设置绑定,如:
绑定必须是双向的,以便文本框从viewmodel更新自己
在您的代码隐藏中,您有一个属性
ServerIP
,我认为您希望将其命名为PropY
,因为您的TextBox
绑定到PropY
属性 .此外,您应该在 ExecuteResetFormCommand 命令中为您的属性分配值,而不是您的私有成员,因为私有成员不会触发
INotifyPropertyChanged