【问题标题】:Fire event when ItemsSource of ListView changesListView 的 ItemsSource 发生变化时触发事件
【发布时间】:2011-11-27 22:08:37
【问题描述】:

我找不到可以在加载窗口后调用的事件,也找不到可以访问 ListView 的 ItemsSource 的位置。我唯一能想到的是 ListView 中的 Loaded 事件,但是当这个事件被触发时,ItemsSource 保持为空。

我可能需要另一个事件,这样我才能知道 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,为什么还要在视图中做某事?
  • 我想做的是根据绑定到 ListView 的集合自动生成列...这就是为什么我要这样做的原因。我对 DependencyProperties 没有太多经验,这是第一个想法,这就是为什么我试图找到要调用的适当事件,该事件查看集合中的字符串数组(通过 ItemsSource)并添加一个 GridView ListView 的列。
  • 尝试覆盖 OnApplyTemplate,但为什么您可能需要在其他地方使用该解决方案?

标签: c# wpf xaml data-binding dependency-properties


【解决方案1】:

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

【讨论】:

  • 您的意思是 DependencyPropertyDescriptor?我现在有点困惑,它是如何工作的,应该应用在哪里?
  • @Miguel:例如,您可以在窗口的构造函数中订阅,或者在 ListView 的加载事件中订阅。
  • 成功了。谢谢!我最近才开始使用 DependencyProperties,所以我没有任何使用它们的经验,也不知道我们必须做什么,但它们确实很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多