2010-08-06 76 views
1

我正在使用WinForms屬性網格來顯示對象的屬性。但是,大多數屬性都是隻讀的,因此顯示爲灰色而不是黑色。有沒有辦法自定義使用的顏色?我希望禁用的屬性更容易閱讀。更改屬性網格中的只讀屬性的前景色

順便說一句:我認爲this question的答案可能與我想要做的事情有關。但我不確定我如何訪問ControlPaint.DrawStringDisabled

回答

1

不幸的是,沒有內置的方法來改變顏色。與許多標準的.NET控件一樣,它們僅僅是它們的COM等價物的封裝版本。

這意味着在實踐中是很多,如果不是所有的畫都是由COM組件完成的,因此,如果您嘗試重寫.NET OnPaint方法,並呼籲ControlPaint.DrawStringDisabled或任何其他繪畫代碼,它更可能會產生不希望的效果,或者甚至沒有效果。

的選項有:

  1. 從頭開始建立一個自定義的控制(可能是最容易)
  2. 覆蓋WndProc並試圖攔截繪製消息(不能保證工作)
  3. 嘗試覆蓋OnPaint和做你的畫上(不保證工作)

對不起,這可能不是你想要的答案,但我想不出更簡單的方法。我從痛苦的經歷中知道,這種事情很難修改。

11

此問題有一個簡單的解決方案。

只是降低中的R爲RGB PropertyGrid的的forcolor,像這樣:

Me.PropertyGrid2.ViewForeColor = Color.FromArgb(1, 0, 0) 

此功能只作用於黑色。

+0

+1。這工作! – Ben 2012-10-10 05:04:44

+2

這到底是怎麼做的?這是hackish,但給了預期的結果。什麼時候會失敗以及如何? – 2016-04-28 17:41:53

0

這是什麼巫術? +1!我見過其他解決方案,陷入鼠標和鍵盤。這是迄今爲止最好也是最簡單的解決方案。這是我繼承的只讀控件的片段。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.ComponentModel; 
using System.Drawing; 

namespace MyCustomControls 
{ 
    public sealed class ReadOnlyPropertyGrid : System.Windows.Forms.PropertyGrid 
    { 
     #region Non-greyed read only support 
     public ReadOnlyPropertyGrid() 
     { 
      this.ViewForeColor = Color.FromArgb(1, 0, 0); 
     } 
     //--- 
     private bool _readOnly; 
     public bool ReadOnly 
     { 
      get { return _readOnly; } 
      set 
      { 
       _readOnly = value; 
       this.SetObjectAsReadOnly(this.SelectedObject, _readOnly); 
      } 
     } 
     //--- 
     protected override void OnSelectedObjectsChanged(EventArgs e) 
     { 
      this.SetObjectAsReadOnly(this.SelectedObject, this._readOnly); 
      base.OnSelectedObjectsChanged(e); 
     } 
     //--- 
     private void SetObjectAsReadOnly(object selectedObject, bool isReadOnly) 
     { 
      if (this.SelectedObject != null) 
      { 
       TypeDescriptor.AddAttributes(this.SelectedObject, new Attribute[] { new ReadOnlyAttribute(_readOnly) }); 
       this.Refresh(); 
      } 
     } 
     //--- 
     #endregion 
    } 
}