C# 模型属性更改时WPF调用方法
这是我长期面临的问题。C# 模型属性更改时WPF调用方法,c#,wpf,properties,model,binding,C#,Wpf,Properties,Model,Binding,这是我长期面临的问题。 假设我们有一个名为Person的POCO类(INotifyPropertyChanged是使用Foldy及其[AddNotifyPropertyChangedInterface]属性提供的) 在ViewModel中,我引用这个类作为属性 public class SomeViewModel { public Person Person { get => person; set { person=
假设我们有一个名为Person的POCO类(INotifyPropertyChanged是使用Foldy及其[AddNotifyPropertyChangedInterface]属性提供的) 在ViewModel中,我引用这个类作为属性
public class SomeViewModel
{
public Person Person
{
get => person;
set
{
person= value;
SomeMethod();
}
}
// Rest of the code
}
问题是当文本框中的名字改变时,我如何调用“SomeMethod”。
Textbox绑定到属性,如下所示:
<TextBox Text="{Binding Person.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged)/>
但问题在于用户表单中的验证,因为我使用POCO类中的数据注释属性进行验证
提前感谢您的帮助和时间 在我看来,有两个选项可供您实现您的目标:
xmlns:i=”http://schemas.microsoft.com/expression/2010/interactivity"
public ICommand YourMethodInvewModel{get;set;}
您必须收听
个人的属性更改
:
public class SomeViewModel
{
public ViewModel()
{
this.Person = new Person();
}
public Person Person
{
get => this.person;
set
{
if (this.Person != null)
{
this.Person.PropertyChanged -= OnPersonFirstNameChanged;
}
this.person= value;
if (this.Person != null)
{
this.Person.PropertyChanged += OnPersonFirstNameChanged;
}
}
}
public void OnPersonFirstNameChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Person.FirstName))
{
SomeMethod();
}
}
}
或者实现一个
Person.FirstNameChanged
事件,该事件Person
可以引发。这提高了可读性。PropertyChanged
主要用于数据绑定引擎。由于必须打开PropertyChangedEventArgs.PropertyChanged
才能发现发生了什么,因此无法处理这次活动非常优雅。感谢@Thế Long为我指出了正确的方向,对于那些面临同样问题的人——我使用“SourceUpdate”事件来设置绑定延迟
xmlns:i=”http://schemas.microsoft.com/expression/2010/interactivity"
感谢您为我指明了正确的方向-解决方案非常接近:)
public string FirstName
{
get => firstName;
set
{
firstName= value;
Person.FirstName=value;
SomeMethod();
}
}
public class PersonViewModel
{
private string _firstName;
public string FirstName
{
get => _firstName;
set
{
_firstName = value;
SomeMethod();
}
}
public ICommand YourMethodInViewModel{get;set;}
public class SomeViewModel
{
public ViewModel()
{
this.Person = new Person();
}
public Person Person
{
get => this.person;
set
{
if (this.Person != null)
{
this.Person.PropertyChanged -= OnPersonFirstNameChanged;
}
this.person= value;
if (this.Person != null)
{
this.Person.PropertyChanged += OnPersonFirstNameChanged;
}
}
}
public void OnPersonFirstNameChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Person.FirstName))
{
SomeMethod();
}
}
}
xmlns:i = "http://schemas.microsoft.com/expression/2010/interactivity"
<TextBox Text={Binding = " ..., Delay=500"}>
<i:Interactivity.Triggers>
<i:EventTrigger EventName="SourceChanged">
<i:InvokeCommandAction Commmand="{Binding SomeMethodCommand}"/>
</i:EventTrigger>
</i:Interactivity.Triggers>
</TextBox>