Update automatic ListBox items when alter List

前端 未结 3 1470
南旧
南旧 2021-01-27 07:16

I have a ListBox, I populate it with ItemsSource with List.

But when I delete or add new control for this List, I need every tim

相关标签:
3条回答
  • 2021-01-27 07:52

    In your Xaml, use something like this...

    <ListBox ItemsSource="{Binding MyItemsSource}"/>
    

    And wire it up like this...

    public class ViewModel:INotifyPropertyChanged
        {
            public ObservableCollection<Control> MyItemsSource { get; set; }
            public ViewModel()
            {
                MyItemsSource = new ObservableCollection<Control> {new ListBox(), new TextBox()};
            }
            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropertyChanged(string name)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(name));
                }
            }
        }
    

    This will present the items to the ListBox. In the example here, the collection contains a ListBox and a TextBox. You can add/delete from the collection and get the behaviour you are after. Controls themselves are not all that great as ListBox items because they do not have a meaningful way of populating a visual. So you will probably need to run them through an IValueConverter.

    0 讨论(0)
  • 2021-01-27 08:05

    Implement INotifyPropertyChanged interface in your viewmodel. Post that in the setter of this List, call the NotifyPropertyChanged event. This will result in updating your changes on UI

    0 讨论(0)
  • 2021-01-27 08:10

    Instead of using a List<T>, use an ObservableCollection<T>. It is a list that supports change notifications for WPF:

    // if this isn't readonly, you need to implement INotifyPropertyChanged, and raise
    // PropertyChanged when you set the property to a new instance
    private readonly ObservableCollection<Control> items = 
        new ObservableCollection<Control>();
    
    public IList<Control> Items { get { return items; } }
    
    0 讨论(0)
提交回复
热议问题