问题
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