添加\从ListView中删除但不反映在UI中

时间:2012-12-27 06:04:45

标签: wpf listview binding

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

2 个答案:

答案 0 :(得分:2)

您应该将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));
        }
    }
}

答案 1 :(得分:0)

您应该将List<T>更改为ObservableCollection<T>BindingList<T>

原因,列表未实现INotifyPropertyChanged