2011-05-05 35 views
0

對不起,我的英文。 我嘗試編寫由TextBox,Popup和ListBox組成的UserControl(SearchTextBox ... simmillar Firefox搜索文本框)。我需要在我的應用程序中動態更改ListBox的ItemsSource。所以我用的DependencyProperty在用戶控件:DependencyProperty PropertyChangedCallback問題

//STextBox UserControl Code-Behind 
public partial class STextBox : UserControl 
{ 
    public static readonly DependencyProperty ItemsSourceProperty; 

    static STextBox() 
    { 
     ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(STextBox), 
      new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, new PropertyChangedCallback(OnItemsSourceChanged))); 
    } 

    public IEnumerable ItemsSource 
    { 
     get 
     { 
      return (IEnumerable)GetValue(STextBox.ItemsSourceProperty); 
     } 
     set 
     { 
      SetValue(STextBox.ItemsSourceProperty, value); 
     } 
    } 

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     STextBox c = (STextBox)d; 
     c.ItemsSource = (IEnumerable)e.NewValue; 
    } 

我不能使用綁定在我的應用程序的ItemsSource,因爲兩個列表我的列表框-的ItemsSource創建從數據庫中記錄的飛行。我在代碼中設置的ItemsSource: //我的應用程序的代碼隱藏

switch (SomeIF) 
     { 
      case 0: 
       sTextBox.ItemsSource = list1; 
       break; 

      case 1: 
       sTextBox.ItemsSource = list2; 
       break; 
     } 

但是什麼都沒有發生。我確切地知道OnItemsSourceChanged方法被觸發,但新的值從未分配給ItemsSource。我做錯了什麼?

+1

如何使用UserControl的ItemsSource屬性?你把它綁定在某個地方嗎? – 2011-05-05 10:49:09

+0

不,我沒有使用我的UserControl的綁定 – mirymir 2011-05-05 10:52:43

+0

那麼當你分配ItemsSource時,你期望發生什麼?如果這個屬性沒有在任何地方使用,當然沒有什麼會發生......你可能需要將它綁定到ListBox的ItemsSource屬性。 – 2011-05-05 10:58:24

回答

1

不能說我喜歡,但這個解決方案工作。

private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    STextBox c = (STextBox)d; 
    c.OnItemsSourceChanged(e); 
} 

//added overload method where I can simply set property to the control 
protected virtual void OnItemsSourceChanged(DependencyPropertyChangedEventArgs e) 
{ 
    myListBox.ItemsSource = ItemsSource; 
} 
相關問題