2017-06-14 45 views
0

我有一個DataGridView,我用BindingList填充。 BindingList是一個類型爲SyncDetail的列表,它有許多屬性。在這些屬性,我可以使用屬性來決定是否不顯示的列(Browsable(false)),列(DisplayName("ColumnName"))的顯示名稱等請參見下面的例子:使用屬性來指定一列FillWeight

public class SyncDetail : ISyncDetail 
{ 

    // Browsable properties 

    [DisplayName("Sync Name")] 
    public string Name { get; set; } 

    // Non browsable properties 

    [Browsable(false)] 
    [XmlIgnore] 
    public bool Disposed { get; set; } 
} 

有沒有一種方法,我可以使用屬性來定義列的寬度應該設置爲?例如[ColumnWidth(200)]。如果可能,我想設置FillWeight,因爲我的AutoSizeColumnsMode設置爲Fill

謝謝。

+0

你想要的是一個屬性來爲你設置一個最大長度屬性? –

回答

0

我結束了實現一個自定義屬性來做到這一點。

public class ColumnWeight : Attribute 
    { 
     public int Weight { get; set; } 

     public ColumnWeight(int weight) 
     { 
      Weight = weight; 
     } 
} 

,然後我可以只重寫我的DataGridView的OnColumnAdded方法來獲取屬性和設置FillWeight的列。

protected override void OnColumnAdded(DataGridViewColumnEventArgs e) 
{ 
    // Get the property object based on the DataPropertyName of the column 
    var property = typeof(SyncDetail).GetProperty(e.Column.DataPropertyName); 
    // Get the ColumnWeight attribute from the property if it exists 
    var weightAttribute = (ColumnWeight)property.GetCustomAttribute(typeof(ColumnWeight)); 
    if (weightAttribute != null) 
    { 
     // Finally, set the FillWeight of the column to our defined weight in the attribute 
     e.Column.FillWeight = weightAttribute.Weight; 
    } 
    base.OnColumnAdded(e); 
} 

然後,我可以在我的對象的屬性上設置屬性。

public class SyncDetail : ISyncDetail 
{ 

    // Browsable properties 

    [DisplayName("Sync Name")] 
    [ColumnWeight(20)] 
    public string Name { get; set; } 

    etc... 
}