Change the foreground color of read-only properties in a propertygrid

最后都变了- 提交于 2019-12-06 15:45:52
Matt B

Unfortunately, there's no built-in way to change the colour. As with a lot of the standard .NET controls, they're merely wrapped versions of their COM equivalents.

What this means in practice is that a lot, if not all of the painting is done by the COM component, so if you try overriding the .NET OnPaint method and calling ControlPaint.DrawStringDisabled or any other painting code, it's more than likely going to have an undesired effect, or no effect what-so-ever.

Your options are:

  1. Build a custom control from scratch (probably the easiest)
  2. Override WndProc and try to intercept paint messages (not guaranteed to work)
  3. Attempt to override OnPaint and do your painting on top (not guaranteed to work)

Sorry that's probably not the answer you wanted, but I can't think of an easier method. I know from bitter experience that this sort of thing can be hard to modify.

Mohammad Es-haghi

This problem has a simple solution.

Just reduce R in the RGB for forcolor of the PropertyGrid, like this:

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

This feature just acts on black color.

What sorcery is this? +1! I have seen other solutions that trap mouse and keyboard. This is by far the best and easiest solution. Here is a snippet of my inherited read-only control.

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!