开发者

DependencyProperty PropertyChangedCallback problem

开发者 https://www.devze.com 2023-03-03 16:58 出处:网络
Sorry for my English. I try to write UserControl (SearchTextBox...开发者_如何学Pythonsimmillar Firefox search textbox) that consists from TextBox, Popup and ListBox in a Popup. I need to change Items

Sorry for my English. I try to write UserControl (SearchTextBox...开发者_如何学Pythonsimmillar Firefox search textbox) that consists from TextBox, Popup and ListBox in a Popup. I need to change ItemsSource of ListBox dynamically in my application. So i use DependencyProperty in UserControl:

//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;
   }

I can't use bindings to ItemsSource in my app, because two lists for my ListBox-ItemsSource creates on the fly from records of database. I set ItemsSource in code: //my app code-behind

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

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

But nothing happened. I know exactly that OnItemsSourceChanged method is fired, but new value never assigned to ItemsSource. What I'am doing wrong?


Can not say that I liked, but this solution work.

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消