C# 当ListView的ItemsSource更改时引发事件

C# 当ListView的ItemsSource更改时引发事件,c#,wpf,xaml,data-binding,dependency-properties,C#,Wpf,Xaml,Data Binding,Dependency Properties,我找不到在加载窗口后可以调用的事件,也找不到可以访问ListView的ItemsSource的事件。我唯一能想到的是ListView中已加载的事件,但当触发此事件时,ItemsSource仍然为null 我可能需要另一个活动,以便知道ItemsSource中包含的内容 因此,通过代码,我可能会更好地公开我正在尝试做的事情: 在自定义类中: public class GridViewSomething { public static readonly DependencyProperty

我找不到在加载窗口后可以调用的事件,也找不到可以访问ListView的ItemsSource的事件。我唯一能想到的是ListView中已加载的事件,但当触发此事件时,ItemsSource仍然为null

我可能需要另一个活动,以便知道ItemsSource中包含的内容

因此,通过代码,我可能会更好地公开我正在尝试做的事情:

在自定义类中:

public class GridViewSomething
{
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("Test",
        typeof(bool),
        typeof(GridViewSomething),
        new UIPropertyMetadata(OnTestChanged));

    public static bool GetTest(DependencyObject obj)
    {
        return (bool)obj.GetValue(TestProperty);
    }

    public static void SetTest(DependencyObject obj, bool value)
    {
        obj.SetValue(TestProperty, value);
    }

    static void OnTestChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        ListView listView = sender as ListView;

        if (!(bool)e.OldValue && (bool)e.NewValue)
            listView.AddHandler(ListView.LoadedEvent, new RoutedEventHandler(ListView_Loaded));
        else if (!(bool)e.NewValue && (bool)e.OldValue)
            listView.RemoveHandler(ListView.LoadedEvent, new RoutedEventHandler(ListView_Loaded);
    }

    static void ListView_Loaded(object sender, RoutedEventArgs e)
    {
        ListView listView = sender as ListView;

        if (listView.ItemsSource != null)
        {
            //Do some work
        }
    }
}
以及ListView:

(...)

<ListView ItemsSource="{Binding Students}"
          test:GridViewSomething.Test="True">

(...)
(…)
(...)
我正在将ListView绑定到此窗口的ViewModel中的集合。我需要准确地知道定制类中ItemsSource中的内容

那么我如何才能做到这一点呢


提前谢谢

您可以使用描述符对
ItemsSource
属性上的更改进行subscription。如果检查该处理程序中的值,则该值不应为null(除非绑定属性实际上设置为null)。

您已经知道绑定集合是ItemsSource,为什么需要它在视图中执行某些操作?我尝试的是根据绑定集合自动生成列到ListView。。。这就是为什么我想这样做。我对DependencyProperties没有太多经验,这是我的第一个想法,这就是为什么我试图找到要调用的适当事件,该事件查看集合中的字符串数组(通过ItemsSource),并向ListView添加带有列的GridView,但是为什么您需要在其他地方使用该解决方案?您是指DependencyPropertyDescriptor?我现在有点困惑,它是如何工作的,应该在哪里应用?@Miguel:你可以在窗口的构造函数中订阅,或者在ListView的加载事件中订阅。它工作了。谢谢我最近才开始使用DependencyProperties,所以我没有任何使用它们的经验,也不知道我们需要做什么,但它们真的很有用。