当属性改变时,UserControl触发事件

本文关键字:事件 UserControl 属性 改变 | 更新日期: 2023-09-27 18:05:31

DocField有一个公共bool属性IsSelected
DocField实现INotifyPropertyChanged

DocField.IsSelected发生变化时,我需要一个在UserControlDocFieldBaseB中触发的事件。

我该怎么做?

public partial class UserControlDocFieldBaseB : UserControl
{
    private DocField docField = null;
    public UserControlDocFieldBaseB(DocField DocField)
    {
        InitializeComponent();
        docField = DocField;
    }

根据dkozl的评论,我是这样连接的
UserControlDocFieldString是相当昂贵的所以我只想在需要时加载它

我怀疑我可以使用加载的事件,而不是UserControl1_DataContextChanged,但这似乎工作
它也适用于Loaded事件

public UserControlDocFieldBaseB()
{
    InitializeComponent();
    DataContextChanged += new DependencyPropertyChangedEventHandler(UserControl1_DataContextChanged);
}
void UserControl1_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if (sender is UserControlDocFieldBaseB)
    {
        UserControlDocFieldBaseB uc = (UserControlDocFieldBaseB)sender;
        if (uc.DataContext is DocFieldString)
        {
            if (docFieldString == null)
            {
                docFieldString = (DocFieldString)uc.DataContext;
                docFieldString.PropertyChanged += DocFieldString_PropertyChanged;
            } 
        }
    }
}
void DocFieldString_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    switch (e.PropertyName)
    {
        case "IsSelected":
            //MessageBox.Show(docFieldString.Name + " docFieldString.IsSelected " + docFieldString.IsSelected.ToString());
            if (userControlDocFieldString == null && docFieldString != null && docFieldString.IsSelected)
            {
                userControlDocFieldString = new UserControlDocFieldString(docFieldString);
                this.frmEdit.Content = userControlDocFieldString;
            }
            break;
    }
}

当属性改变时,UserControl触发事件

由于DocField实现了INotifyPropertyChangedIsSelected属性,您可以简单地订阅DocFieldPropertyChanged事件,例如当控件被加载或DocField属性被更改时,如果它是为' IsSelected属性传递事件

private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (String.IsNullOrEmpty(e.PropertyName) || e.PropertyName == "IsSelected")
    {
        //pass on the event
    }
}