【问题标题】:Adding\Removing from ListView but not reflecting in UI从 ListView 添加\删除但不反映在 UI 中
【发布时间】:2012-12-12 13:48:47
【问题描述】:

我有两个List<ColumnClass>。一个用于左侧列表视图,另一个用于右侧列表视图。这些列表视图在一个弹出框中。我正在修改两个 Listview 的列表,并再次将其分配给 Listview 的 ItemsSource。但这并没有立即反映在 UI 中。当我关闭弹出窗口并再次打开时,它会反映更改。我错过了什么?

【问题讨论】:

    标签: wpf listview binding


    【解决方案1】:

    您应该将List<T> 替换为ObservableCollection<T>,ObservableCollections 将在删除项目时更新您的ListView,如果您只是修改您的ColumnClass 的属性,请确保您的ColumnClass 实现INotifyPropertyChanged 这将允许属性更改时更新的 UI。

    例子:

    代码:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MyColumns.Add(new ColumnClass { Name = "Column1" });
            MyColumns.Add(new ColumnClass { Name = "Column2" });
            MyColumns.Add(new ColumnClass { Name = "Column3" });
        }
    
        private ObservableCollection<ColumnClass> _myColumns = new ObservableCollection<ColumnClass>();
        public ObservableCollection<ColumnClass> MyColumns
        {
            get { return _myColumns; }
            set { _myColumns = value; }
        }
    }
    

    xaml:

    <Window x:Class="WpfApplication8.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="WpfApplication8" Height="368" Width="486" Name="UI" >
        <Grid>
            <ListView ItemsSource="{Binding ElementName=UI, Path=MyColumns}" DisplayMemberPath="Name" />
        </Grid>
    </Window>
    

    型号:

    public class ColumnClass : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged("Name"); }
        }
    
    
    
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// Notifies the property changed.
        /// </summary>
        /// <param name="property">The info.</param>
        public void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您应该将List&lt;T&gt; 更改为ObservableCollection&lt;T&gt;BindingList&lt;T&gt;

      原因,List 没有实现INotifyPropertyChanged

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多