【问题标题】:Update automatic ListBox items when alter List<T>更改 List<T> 时更新自动 ListBox 项
【发布时间】:2026-02-20 10:25:02
【问题描述】:

我有一个列表框,我用ItemsSourceList&lt;Control&gt; 填充它。

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

有什么方法可以让ListBox同步List内容吗?

【问题讨论】:

标签: c# wpf list


【解决方案1】:

不要使用List&lt;T&gt;,而是使用ObservableCollection&lt;T&gt;。这是一个支持 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; } }

【讨论】:

    【解决方案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 运行它们。

    【讨论】:

      【解决方案3】:

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

      【讨论】: