UserControl Fire Event when a property changes

萝らか妹 提交于 2019-12-11 12:59:56

问题


DocField has a public bool property IsSelected
DocField implements INotifyPropertyChanged

I need an event that fires in UserControlDocFieldBaseB when DocField.IsSelected changes.

How do I do that?

public partial class UserControlDocFieldBaseB : UserControl
{
    private DocField docField = null;

    public UserControlDocFieldBaseB(DocField DocField)
    {
        InitializeComponent();
        docField = DocField;
    }

Based on the comment from dkozl this is how I wired it up
UserControlDocFieldString is a fairly expensive so I only want to load it on demand

I suspect I could use the Loaded event rather than the UserControl1_DataContextChanged but this seems to work
It also works with the Loaded event

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;
    }
}

回答1:


Since DocField implements INotifyPropertyChanged for IsSelected property you can simply subscribe to PropertyChanged event of DocField, for example when control is loaded or DocField property is changed and pass on the event if it's for `IsSelected property

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


来源:https://stackoverflow.com/questions/23898714/usercontrol-fire-event-when-a-property-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!