DependencyProperty PropertyChangedCallback问题

时间:2011-05-05 10:45:00

标签: wpf dependency-properties

抱歉我的英文。 我尝试编写一个由弹出窗口中的TextBox,Popup和ListBox组成的UserControl(SearchTextBox ... simmillar Firefox搜索文本框)。我需要在我的应用程序中动态更改ListBox的ItemsSource。所以我在UserControl中使用DependencyProperty:

//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绑定,因为我的ListBox-ItemsSource的两个列表是从数据库记录中动态创建的。我在代码中设置了ItemsSource:     //我的应用程序代码隐藏

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

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

但什么都没发生。我确切地知道OnItemsSourceChanged方法被触发,但新值从未分配给ItemsSource。我做错了什么?

1 个答案:

答案 0 :(得分: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;
}