将List <class>绑定到ListBox

时间:2016-11-18 11:25:48

标签: c# wpf data-binding listbox

我有一个List,其中包含此类的一些项目:

public class Entry { public string FileSize; public string Name; public byte[] Data; public UInt64 XXHashFilePath; public UInt32 FileDataOffset; public UInt32 CompressedSize; public UInt32 UncompressedSize; public CompressionType TypeOfCompression; public UInt64 SHA256; public Entry(BinaryReader br) { XXHashFilePath = br.ReadUInt64(); FileDataOffset = br.ReadUInt32(); CompressedSize = br.ReadUInt32(); UncompressedSize = br.ReadUInt32(); TypeOfCompression = (CompressionType)br.ReadUInt32(); SHA256 = br.ReadUInt64(); FileSize = Functions.SizeSuffix(UncompressedSize); } }

我希望我的ListBox按特定顺序在列中显示XXHashFilePath,TypeOfCompression,FileSize,Name。

1 个答案:

答案 0 :(得分:0)

您已将字段更改为属性(如Clemens建议)。这也是使用c#https://msdn.microsoft.com/en-us/library/ms229057(v=vs.110).aspx

的OOP原则

此外,在将条目添加到ListBox的items集合后,属性更改其值时,您可能希望实现INotifyPropertyChanged。如果Entry元素是不可变的并且只是添加到ListBox中(并从中删除),则不必实现INotifyPropertyChanged。

public class EntryViewModel : ViewModelBase
{
    private string _FileSize;
    public string FileSize
    {
        get
        {
            return _FileSize;
        }
        set
        {
            _FileSize = value;
            OnPropertyChanged();
        }
    }
}

使用MVVM模式也是最佳做法。这是一个简单的基类,可以在不使用MVVM框架的情况下开始使用。

public class ViewModelBase : INotifyPropertyChanged
{
    #region Events

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion Events

    #region Methods

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion Methods
}