WPF事件之谜

时间:2015-05-10 08:03:09

标签: c# wpf

我是WPF的新手,我无法理解我的代码的这种行为......我有一类用户控件......

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));

}

我在XAML窗口中使用此自定义控件...

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        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>

当我调试此代码时,

1)构造函数创建ObservableCollection的新实例并注册 UserItems_CollectionChanged 到此实例

2)引发UserItems属性setter,并将UserItems设置为ObservableCollection的 NEW INSTANCE 。此实例不应向其注册 UserItems_CollectionChanged

3)对Menu1和Menu2标签触发事件 UserItems_CollectionChanged 为什么? ObservableCollection的新实例不应该引发此事件!

此代码中或WPF后面有些内容我不明白。你能帮助我吗 ?抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

xaml中的UserItems生成一个“新视图”侧集合,并推送现有的集合。问题可能与采取的方法有关。您可以为集合的setter创建一个事件,并在UI生成新实例并调用setter时触发它。订阅它,然后挂钩你的收藏改变处理程序。