覆盖列表框中的itemsource属性

本文关键字:itemsource 属性 列表 覆盖 | 更新日期: 2023-09-27 18:04:39

我继承了ListBox到我的类,我想覆盖itemsource属性。

当itemsource被赋值时,我实际上想做一些操作。

这怎么可能?

我想在c#代码中,而不是在xaml

覆盖列表框中的itemsource属性

在WPF中重写依赖属性的方式如下....

    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.
        }
    } 

这是你要找的吗?

为什么不在设置项目源属性之前设置SourceUpdated事件处理程序?

例如,如果MyListBox是你的列表框&MyItemSource是源,您可以设置事件处理程序并按如下方式调用它:

void MyFunction()
        {
           MyListBox.SourceUpdated += new EventHandler<DataTransferEventArgs>(MyListBox_SourceUpdated);    
           MyListBox.ItemsSource    = MyItemSource;
        }
void MyListBox_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            // Do your work here
        }

另外,确保您的数据源实现了INotifyPropertyChanged或INotifyCollectionChanged事件。

这里我已经创建了一个自定义列表框,从Listbox扩展,它有一个依赖属性itemssource…

当每一个项目源得到更新时,你可以做你的操作,之后你可以调用customlistbox的updatesourcemmethod,它将分配BaseClass的itemsSource属性。

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