当属性改变时,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;
}
}
由于DocField
实现了INotifyPropertyChanged
的IsSelected
属性,您可以简单地订阅DocField
的PropertyChanged
事件,例如当控件被加载或DocField
属性被更改时,如果它是为' IsSelected属性传递事件
private void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (String.IsNullOrEmpty(e.PropertyName) || e.PropertyName == "IsSelected")
{
//pass on the event
}
}