也许我完全不理解事件。.NET:事件难点
我在Silverlight中构建了Windows Phone 7应用程序。
我有一个UserControl
包装ListBox
,称为EditableListBox
。 ListBox
有一个数据模板。列表框中的项目被包装在EditableListItem
对象中。
数据模板如下:
<DataTemplate>
<Grid ManipulationCompleted="Grid_ManipulationCompleted">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding Path=IconSource}"
Grid.Column="0"
Width="96"
Height="96"
VerticalAlignment="Center"
Visibility="{Binding Path=Editing, Converter={StaticResource visibilityConverter}}"
/>
<TextBlock Text="{Binding Path=Name}" Grid.Column="1" />
</Grid>
</DataTemplate>
我绑定Visibility
每个EditableListItem
的属性,所以我需要实现INotifyPropertyChanged
所以更新为后盾的项目都反映在UI。 (?右或者是有一个更简单的方法来做到这一点?)
EditableListItem
:
public class EditableListItem : INotifyPropertyChanged
{
private EditableListBox _parentListBox;
public event PropertyChangedEventHandler PropertyChanged;
public bool Editing
{
get
{
return _parentListBox.Editing;
}
}
public EditableListItem(Section section, EditableListBox parentListBox)
{
_parentListBox = parentListBox;
// after this line, _parentListBox.PropertyChanged is still null.
// why is that?
_parentListBox.PropertyChanged += PropertyChanged;
_parentListBox.PropertyChanged += new PropertyChangedEventHandler(_parentListBox_PropertyChanged);
}
EditableListBox
:
public partial class EditableListBox : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// NotifyPropertyChanged will raise the PropertyChanged event,
// passing the source property that is being updated.
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void SetSectionsSource(ObservableCollection<Section> sectionsSource)
{
sectionsSource.CollectionChanged += new NotifyCollectionChangedEventHandler(sectionsSource_CollectionChanged);
ContentListBox.ItemsSource = sectionsSource.Select(section => new EditableListItem(section, this) { Enabled = true });
//ContentListBox.ItemsSource.Add(new EditableListItem(new Section("Section", 3)) { Enabled = true });
}
// ...
private bool _editing;
public bool Editing
{
get
{
return _editing;
}
set
{
_editing = value;
NotifyPropertyChanged("Editing");
}
}
}
的Editing
属性存储在EditableListBox
- EditableListItem
只是将其转发。我想连接到EditableListItem.PropertyChanged
直接EditableListBox.PropertyChanged
,但下面不工作:
// after this line, _parentListBox.PropertyChanged is still null.
// why is that?
_parentListBox.PropertyChanged += PropertyChanged;
下面做工作:
_parentListBox.PropertyChanged += new PropertyChangedEventHandler(_parentListBox_PropertyChanged);
这是为什么?第一次尝试完全无效(如果是这样,为什么编译器允许它?)?
感谢您的详细回复。那么,eventA + = eventB'实际上做了什么? – 2010-11-14 19:23:03
我不太确定。从逻辑上讲,它会将附加到'eventB'的所有事件句柄复制到'eventA',但我怀疑这是因为它不应该从类外部访问事件的内容。我将不得不做一些测试。至少它注意到我以前曾经使用过。 – 2010-11-14 19:49:27