2016-11-18 97 views
0

我有一個包含這個類的幾個項目的列表:綁定列表<Class>到ListBox

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

我希望我的列表框在列特定顯示XXHashFilePath,TypeOfCompression,文件大小,名稱訂購。

+1

從這裏開始閱讀:[數據模板概述](https://msdn.microsoft.com/en-us/library/ms742521(v = vs.110).aspx)。首先,你的類的成員應該是公共屬性,而不是字段,以支持數據綁定。 – Clemens

回答

0

你已經改變你的領域屬性(如克萊門斯建議)。這也是一個OOP原理c#https://msdn.microsoft.com/en-us/library/ms229057(v=vs.110).aspx

此外,你可能想要實現INotifyPropertyChanged只是當一個Entry被添加到ListBox的items集合後,屬性更改它們的值時才需要。如果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 
} 
+0

「如果要同步視圖,則必須實現INotifyPropertyChanged接口」僅當屬性在將條目添加到ListBox的項集合後更改其值*時纔是必需的。如果Entry元素是不可變的,並且只是添加到ListBox中(並從中移除),則不必實現INotifyPropertyChanged。 – Clemens

+0

@Clemens好點。 Thx澄清 - >我已將您的評論添加到我的答案中。 – Mat