0

我有一个 ListBox,我ItemsSourceList<Control>.

但是当我为此列表删除或添加新控件时,我每次都需要重置我的 ListBox ItemsSource

有任何 ListBox 同步列表内容的方法吗?

4

3 回答 3

2

不要使用List<T>,而是使用ObservableCollection<T>。它是一个支持 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; } }
于 2013-06-30T01:09:56.607 回答
2

在你的 Xaml 中,使用类似这样的东西......

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

并像这样连接它...

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

这会将项目呈现给 ListBox。在此处的示例中,该集合包含一个 ListBox 和一个 TextBox。您可以从集合中添加/删除并获得您所追求的行为。控件本身并不像 ListBox 项那么好,因为它们没有一种有意义的方式来填充视觉对象。因此,您可能需要通过 IValueConverter 运行它们。

于 2013-06-30T01:18:49.437 回答
0

在您的视图模型中实现 INotifyPropertyChanged 接口。将其发布到此列表的设置器中,调用 NotifyPropertyChanged 事件。这将导致更新您对 UI 的更改

于 2013-06-30T02:19:10.077 回答