簡體   English   中英

將System.Windows.Controls存儲到字典中

[英]Store System.Windows.Controls into a dictionary

我需要一個將Type作為鍵並將Control作為值的字典。 例如,對於字符串類型,控件將為TextBox; 對於布爾類型,控件將是單選按鈕,依此類推...問題是當我聲明諸如Dictionary<Type, Control>類的Dictionary<Type, Control>並嘗試添加TextBox時,例如,它說TextBox是一種類型,即在給定的上下文中無效。 有任何想法嗎?

您必須聲明Dictionary<Type, Type>而不是Dictionary<Type, Control>因為TextBoxType

private static Dictionary<Type, Type> s_ControlTypes = new Dictionary<Type, Type>() {
  {typeof(string), typeof(TextBox)},
  {typeof(bool), typeof(RadioButton)},
};

然后用

// Let's create a control for, say, `bool` type:
Control ctrl = Activator.CreateInstance(s_ControlTypes[typeof(bool)]) as Control;
  Dictionary<Type, Control> dictionary = new Dictionary<Type, Control>();
  dictionary.Add(typeof(string), textBox);
  dictionary.Add(typeof(bool), checkBox);

看起來您正在嘗試將Control類型(從字面上看)添加到字典中,該字典應包含Control實例:

var dictionary = new Dictionary<Type, Control>();
dictionary.Add(typeof(string), TextBox);

你做不到 您需要放置Control特定實例,或者,如果這只是一些映射以供進一步參考,請重新聲明字典:

var dictionary = new Dictionary<Type, Type>();

並用類型填充它:

dictionary.Add(typeof(string), typeof(TextBox));
// and so on

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM