I am new in WPF and I am unable to understand this behavior of my code... I have a class of user control...
public class CustomControl1 : Control
{
.... some code here ...
/// <summary>
/// Constructor
/// </summary>
public CustomControl1()
{
// user items
UserItems = new ObservableCollection<Label>();
UserItems.CollectionChanged += UserItems_CollectionChanged;
}
// informace o pridani do kolekce
void UserItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// !! ?? WHY IS THIS EVENT FIRED AFTER XAML SETS UserItems PROPERTY TO NEW INSTANCE ??
}
/// <summary>
/// User items
/// </summary>
public ObservableCollection<Label> UserItems
{
get { return (ObservableCollection<Label>)GetValue(UserItemsProperty); }
set
{
// XAML code sets this value with new instance of ObservableCollection !
SetValue(UserItemsProperty, value);
}
}
// Using a DependencyProperty as the backing store for UserItems. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UserItemsProperty =
DependencyProperty.Register("UserItems", typeof(ObservableCollection<Label>), typeof(CustomControl1), new UIPropertyMetadata(null));
}
I use this custom control in XAML window...
<Window
xmlns="http://ift.tt/o66D3f"
xmlns:x="http://ift.tt/mPTqtT"
xmlns:c="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1" x:Class="WpfApplication1.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid>
<c:CustomControl1>
<c:CustomControl1.UserItems>
<Label>Menu1</Label>
<Label>Menu2</Label>
</c:CustomControl1.UserItems>
</c:CustomControl1>
</Grid>
</Window>
When I debug this code,
1) Constructor creates new instance of ObservableCollection and registers UserItems_CollectionChanged. to this instance.
2) UserItems property setter is raised and UserItems is set to a NEW INSTANCE of ObservableCollection. This instance should not have UserItems_CollectionChanged registered to it.
3) Event UserItems_CollectionChanged is fired for Menu1 and Menu2 labels. WHY? new instance of ObservableCollection should not raise this events !
There is something in this code or behind WPF what I do not understand. Can you help me ? Sorry for my bad English.
Aucun commentaire:
Enregistrer un commentaire