属性更改时的UserControl Fire事件

时间:2014-05-27 20:51:55

标签: c# .net wpf event-handling

DocField有一个公共布尔属性IsSelected
DocField实现了INotifyPropertyChanged

我需要在UserControlDocFieldBaseB更改DocField.IsSelected时触发的事件。

我该怎么做?

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

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

基于dkozl的评论,这是我如何连接它的 UserControlDocFieldString相当昂贵,所以我只想按需加载它

我怀疑我可以使用Loaded事件而不是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;
    }
}

1 个答案:

答案 0 :(得分:1)

由于DocFieldINotifyPropertyChanged属性实现IsSelected,您只需订阅PropertyChanged DocField事件,例如加载控件或{{1}如果属性为'IsSelected属性

,则属性被更改并传递给事件
DocField