也許我完全不理解事件。.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