[英]Readonly PropertyGrid
我在我正在編寫的應用程序中使用 PropertyGrid 以允許用戶查看並有時編輯我的對象的實例。 有時,用戶可能以讀/寫模式打開文件,他們可以通過屬性網格對該文件進行更改。 在其他情況下,他們可能有一個以只讀模式打開的文件,並且不應該能夠通過 PropetyGrid 對對象進行任何更改。 我的類也有通過實現 ICustomTypeDescriptor 返回的動態屬性。 這就是為什么我真的想利用 PropertyGrid 控件的內置靈活性。
似乎沒有一種簡單的方法可以將屬性網格設置為只讀模式。 如果我禁用 PropertyGrid,這也會阻止用戶滾動列表。 所以我認為最好的方法是在運行時將 ReadOnlyAttributes 添加到屬性中。 還有別的辦法嗎?
我找到了一個非常快速的解決方案,對於那些不關心屬性被灰化的人來說。
TypeDescriptor.AddAttributes(myObject, new Attribute[]{new ReadOnlyAttribute(true)});
propertyGrid1.SelectedObject = myObject;
由於您正在實現ICustomTypeDescriptor
因此無需添加任何屬性; 你可以在PropertyDescriptor
上覆蓋IsReadOnly
。 我認為編寫一個模仿(通過ICustomTypeDescriptor
和TypeConverter
)一個包裝類型的中間類型應該很簡單,但總是返回readonly PropertyDesciptor
實例? 如果你想要一個例子,請告訴我(雖然這不是微不足道的 )。
您可能還需要檢查是否東西像這樣提供它建造它。
我的建議是編寫一個繼承自propertygrid控件的自定義控件,並在該自定義控件中具有readonly的布爾值,然后覆蓋一些內容並檢查,if(readonly)然后取消操作
我遇到了這個。 我想要一個只讀但不會變灰的控件。
繼承屬性網格控件並通過添加以下代碼來創建您自己的只讀版本以覆蓋按鍵
#Region "Non-greyed read only support"
Private isReadOnly As Boolean
Public Property [ReadOnly]() As Boolean
Get
Return Me.isReadOnly
End Get
Set(ByVal value As Boolean)
Me.isReadOnly = value
End Set
End Property
Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean
If Me.isReadOnly Then Return True
Return MyBase.ProcessDialogKey(keyData)
End Function
Public Function PreFilterMessage(ByRef m As Message) As Boolean
If m.Msg = &H204 Then 'WM_RBUTTONDOWN
If Me.isReadOnly Then Return True
End If
Return False
End Function
#End Region
I ended up inheriting from PropertyGrid and select the parent category whenever a property is selected.
簡單且無需使用 TypeDescriptor。
public class ReadOnlyPropGrid : PropertyGrid
{
public ReadOnlyPropGrid()
{
this.ToolbarVisible = false; // categories need to be always visible
}
protected override void OnSelectedGridItemChanged(SelectedGridItemChangedEventArgs e)
{
if (e.NewSelection.GridItemType == GridItemType.Property)
{
if (e.NewSelection.Parent != null && e.NewSelection.Parent.GridItemType == GridItemType.Category)
{
this.SelectedGridItem = e.NewSelection.Parent;
return;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.