为自定义 DependencyProperty 手动调用 OnPropertyChanged

Manually invoking OnPropertyChanged for custom DependencyProperty

所以我有一个像这样的自定义 DependencyProperty:

public class PatientLookUp : TextBox
{
    public static readonly DependencyProperty PatientProperty = DependencyProperty.Register("Patient", typeof(Patient), typeof(PatientLookUp), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true });

    public Patient Patient
    {
        get { return (Patient)GetValue(PatientProperty); }
        set { SetValue(PatientProperty, value); }
    }

    //some logic for getting the Patient...
}

编辑:它是在 CustomControl 中定义的。使用此 CustomControl 的另一个控件绑定 Patient 属性 并侦听它的更改事件。问题是,我做了一些网络请求,如果我得到一个 null Patient,我仍然想通知另一个控件 CustomControl 已经完成了它的事情,即使 Patient 没有真正改变。 所以现在我想手动调用 PropertyChanged 事件。有什么办法吗?

希望你能帮助我,谢谢。

Edit2:我的 XAML 绑定患者(缩短):

<Window Name="MyWindow">
    <Grid>
        <llc:PatientLookUp Patient="{Binding Patient}" MaxLength="10" Text="{Binding SocialSecurityNumber}" />
    </Grid>
<Window>

现在我需要通知 MyWindow 的 ViewModel,以防 PatientLookUp 的 Patient 对象发生变化。 LookUp 有一个请求逻辑在按下回车键时触发。请求完成后,我想通知 MyWindow 的 ViewModel,即使它找不到任何人并且值仍然为 null。

您的 class 需要继承 INotifyPropertyChanged 接口并实现它的 classes。完成后,您应该能够在 属性 的集合上调用 OnPropertyChanged 方法。

正在继承 INotifyPropertyChanged:

public partial class MainWindow : INotifyPropertyChanged

INotifyPropertyChanged 的​​实现:

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

调用 NotifyPropertyChanged:

public Patient Patient
{
    get { return (Patient)GetValue(PatientProperty); }
    set
    {
        SetValue(PatientProperty, value);
        OnPropertyChanged();
    }
}

您是从标准 WPF TextBox 派生的,并放置了一些完全不合适的东西。

您以非常不方便的方式处理此问题。

相反:使用常规文本框,绑定到 PatientSearchViewModel.SearchString,当 SearchString 更改时,触发搜索(从 ViewModel),如果找到,设置 PatientSearchViewModel.Patient 属性 和 NotifyPropertyChange() 以便 UI 收到更改通知。

你会这样:

DataModel -> View -> ViewModel

而最直接方便的方法是:

DataModel -> ViewModel -> View