2011-02-25 72 views
5

我怎樣才能得到列表框中的itemsourcechangedevent?如何獲取itemsourcechanged事件?列表框

例如,隨後的ItemSource變化從零到利斯塔到數組listB

我知道有沒有這樣的事件。但是有沒有解決方法?

感謝提前:)

+0

在什麼樣的條件,你的ListBox的數據源改變?你可以發佈一些代碼嗎? – 2011-02-25 16:08:02

回答

7

一個常用的(回答)方法是使用Blend SDK中的PropertyChangedTrigger。但是我不喜歡推薦使用其他SDK,除非明確指出SDK已經在使用。

我會暫時假定它在代碼隱藏中需要監聽「ItemsSourceChanged」事件。你可以使用的技術是建立在你的UserControl一個DependencyProperty並將其綁定到你要聽控制的ItemsSource。

private static readonly DependencyProperty ItemsSourceWatcherProperty = 
    DependencyProperty.Register(
     "ItemsSourceWatcher", 
     typeof(object), 
     typeof(YourPageClass), 
     new PropertyMetadata(null, OnItemsSourceWatcherPropertyChanged)); 

private static void OnItemsSourceWatcherPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    YourPageClass source = d As YourPageClass; 
    if (source != null) 
     source.OnItemsSourceWatcherPropertyChanged(); 
} 

private void OnItemsSourceWatcherPropertyChanged() 
{ 
    // Your code here. 
} 

現在給你ListBox有一個名爲「myListBox」你可以設置與看: -

Binding b = new Binding("ItemsSource") { Source = myListBox }; 
SetBinding(ItemsSourceWatcherProperty, b); 
1

有一個在Silverlight沒有ItemsSourceChanged事件。

但是,有一種變通方法。使用RegisterForNotification()中提到的方法this article註冊屬性值更改回調爲ListBox項目源屬性。

+1

我無法描述這種方法有多少種錯誤。它是一種正確的方法(使用依賴屬性回調),但實現非常糟糕。 – AnthonyWJones 2011-02-25 17:37:03