首页 > 解决方案 > 模型属性更改时的 WPF 调用方法

问题描述

这是我长期面临的问题。
假设我们有一个名为 Person 的 POCO 类(INotifyPropertyChanged 是使用 Foldy 及其 [AddINotifyPropertyChangedInterface] 属性提供的)

[AddINotifyPropertyChangedInterface]
public class Person
{ 
        public int Id{ get; set; }

        [StringLength(20)]
        [Required(ErrorMessage = "Field required")]
        public string FirstName { get; set; }


        [Required(ErrorMessage = "Field required")]
        public string LastName{ get; set; }
}

在 ViewModel 中,我将此类引用为属性

public class SomeViewModel
{
   public Person Person
   {
      get => person;
      set
      {
          person= value;
          SomeMethod();
      }
   }
// Rest of the code
}

问题是如何在文本框中更改名字时调用“SomeMethod”。
文本框绑定到属性如下:

<TextBox Text="{Binding Person.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged)/>

我试图解决它绑定到:

 public string FirstName
 {
   get => firstName;
   set
      {
        firstName= value;
        Person.FirstName=value;
        SomeMethod();
      }
 }

但问题在于用户表单中的验证,因为我使用 POCO 类中的数据注释属性进行验证。

提前感谢您的帮助和时间!

标签: c#wpfpropertiesmodelbinding

解决方案


在我看来,有两种选择可以实现您想要的:

  1. 为 Person 创建一个视图模型并将您的方法移动到 FirstName 的设置器。将 Textbox 绑定到 PersonViewModel 的 FirstName 属性,当您更改 TextBox 中的文本时,将调用 SomeMethod()。
公共类 PersonViewModel
{
    私有字符串_firstName;
    公共字符串名字
    {
        得到 => _firstName;
        放
        {
            _firstName = 值;
            某些方法();
        }
}
  1. 在某些情况下,您必须在所有者 ViewModel 中实现 SomeMethod(),然后只需使用交互性绑定到 Textbox 的 TextChanged 事件并将您的方法分配为调用方法。
xmlns:i = "http://schemas.microsoft.com/expression/2010/interactivity"

<TextBox Name="your_textBox" Text={Binding ...}>
    <i:Interactivity.Triggers>
        <i:EventTrigger EventName="TextChanged">
            <i:InvokeCommandAction Commmand="{Binding YourMethodInViewModel, ElementName=your_textbox}", CommandParameter="{Binding ElementName=your_textbox}"/>
        </i:EventTrigger>
    </i:Interactivity.Triggers>
</TextBox>
公共 ICommand YourMethodInViewModel{get;set;}

推荐阅读