开发者

override itemsource property in listbox c#.net

i m inheriti开发者_StackOverflowng ListBox to my class and i want to override itemsource property.

i actually want to do someoperation when itemsource is assigned.

how it is possible?

i want in c# code only not in xaml


The way you override a dependency property in WPF is this way....

    public class MyListBox : ListBox
    {
        //// Static constructor to override.
        static MyListBox()
        {
              ListBox.ItemsSourceProperty.OverrideMetadata(typeof(MyListBox), new FrameworkPropertyMetadata(null, MyListBoxItemsSourceChanged));
        }

        private static void MyListBoxItemsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
             var myListBox = sender as MyListBox;
             //// You custom code.
        }
    } 

Is this what you are looking for?


Why not just set SourceUpdated event handler before setting the item source property?

For Example if MyListBox is your Listbox & MyItemSource is the source, you may set event handler n call it as follows:

void MyFunction()
        {
           MyListBox.SourceUpdated += new EventHandler<DataTransferEventArgs>(MyListBox_SourceUpdated);    
           MyListBox.ItemsSource    = MyItemSource;
        }

void MyListBox_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            // Do your work here
        }

Also, make sure that your data source implements INotifyPropertyChanged or INotifyCollectionChanged events.


Here i have crated a Custom List box which extends from Listbox and it got a dependency property itemssource...

When ever item source got updated you can do your operations and after that you can call the updatesourcemethod of customlistbox which will assign the itemsSource property of BaseClass.

public class CustomListBox : ListBox
    {

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

        // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(CustomListBox), new UIPropertyMetadata(0, ItemsSourceUpdated));

        private static void ItemsSourceUpdated(object sender, DependencyPropertyChangedEventArgs e)
        {
            var customListbox = (sender as CustomListBox);
            // Your Code
            customListbox.UpdateItemssSource(e.NewValue as IEnumerable);
        }

        protected void UpdateItemssSource(IEnumerable source)
        {
            base.ItemsSource = source;
        }
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜