2012-05-22 21 views
1

我正在編寫一個函數,它將採用Control Ctrl作爲Arguement並修改它的Control.Content。 是否有任何方法獲取並設置Content任何Control ??如何獲取WPF中任何控件的「內容」?

代碼:

void RemoveHotKey(Control Ctrl, int KeyIndex) 
{ 
    if (Ctrl.Content.ToString().Substring(KeyIndex, 1) == "_") // System.Windows.Controls.Control does not contain a definition for 'Content' 
    { 
     Ctrl.Content = Ctrl.Content.ToString().Remove(KeyIndex, 1); // System.Windows.Controls.Control does not contain a definition for 'Content' 
    } 
} 
+0

你爲什麼要使用控制類的說法,而不是ContentControl中類參數? – mtijn

回答

2

試試這個:

void RemoveHotKey(ContentControl Ctrl, int KeyIndex) 
{ 
    if (Ctrl.Content.ToString().Substring(KeyIndex, 1) == "_") 
    { 
     Ctrl.Content = Ctrl.Content.ToString().Remove(KeyIndex, 1); 
    } 
} 

看看here

或本:

void RemoveHotKey(Control Ctrl, int KeyIndex) 
{ 
    ContentControl contentCtrl = Ctrl as ContentControl; 
    if (contentCtrl != null && contentCtrl.Content != null) 
    { 
     if (contentCtrl.Content.ToString().Substring(KeyIndex, 1) == "_") 
     { 
      contentCtrl.Content = contentCtrl.Content.ToString().Remove(KeyIndex, 1); 
     } 
    } 
} 

這比使用反射方式更便宜..

+1

+1對於一個非常好的答案與例子![Selected] – Writwick

1

你可以使用反射來檢查其實是否控制有內容財產......

Type t = Ctrl.GetType(); 
PropertyInfo p = t.GetProperty("Content"); 
if (p != null) 
{ 
    string val = p.GetValue(Ctrl, null) ?? ""; 
    val = val.Replace("_", ""); 
    p.SetValue(Ctrl, val, null); 
} 
2

你可以在你的方法的簽名更改爲這個:

void RemoveHotKey(ContentControl Ctrl, int KeyIndex) 

a ContentControl始終有一個Content屬性。

+2

+1非常好,最快的正確答案! – Writwick

相關問題