【发布时间】: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