问题描述
DocField
具有公共bool属性 IsSelected
DocField
实现INotifyPropertyChanged
DocField
has a public bool property IsSelected
DocField
implements INotifyPropertyChanged
当$ <$ c $时,我需要在 UserControlDocFieldBaseB
中触发的事件c> DocField.IsSelected 更改。
I need an event that fires in UserControlDocFieldBaseB
when DocField.IsSelected
changes.
我该怎么做?
public partial class UserControlDocFieldBaseB : UserControl
{
private DocField docField = null;
public UserControlDocFieldBaseB(DocField DocField)
{
InitializeComponent();
docField = DocField;
}
根据dkozl的评论,这是我如何连接它
UserControlDocFieldString是一个相当昂贵的,所以我只想加载它根据需要
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
我怀疑我可以使用Loaded事件而不是UserControl1_DataContextChanged,但这似乎工作
它也适用于加载的事件
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;
}
}
推荐答案
DocField
实现 INotifyPropertyChanged
for IsSelected
属性,您可以简单地订阅 PropertyChanged
事件 DocField
,例如加载控件或 DocField
property is changed and pass on the event if it is for'IsSelected property
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
}
}
这篇关于UserControl Fire属性更改时发生事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!