您好我想缩短此代码:
<div id="txt" contenteditable="true">
<span id="annyoing-html" contenteditable="false">
<span class="badge">I AM ANNOYING</span>
</span>
<span id="annyoing-html" contenteditable="false">
<span class="badge">I AM ANNOYING TOO</span>
</span>
</div>
稍后我会添加更多设置加载,我需要缩短它但我不知道如何。
我试着把这段代码变成这样的字符串:
tb1n.Text = Settings2.Default.tb1n;
tb2n.Text = Settings2.Default.tb2n;
tb3n.Text = Settings2.Default.tb3n;
tb4n.Text = Settings2.Default.tb4n;
tb5n.Text = Settings2.Default.tb5n;
tb6n.Text = Settings2.Default.tb6n;
tb7n.Text = Settings2.Default.tb7n;
tb8n.Text = Settings2.Default.tb8n;
tb9n.Text = Settings2.Default.tb9n;
tb10n.Text = Settings2.Default.tb10n;
tb11n.Text = Settings2.Default.tb11n;
tb12n.Text = Settings2.Default.tb12n;
tb13n.Text = Settings2.Default.tb13n;
但后来我意识到这不是一个好的解决方案,因为从字符串执行代码很难做到而且我不喜欢它。
答案 0 :(得分:2)
您可以创建可视树辅助类并在视图上查找所有文本框实例。
助手类:
public static class TreeHelper
{
public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject
{
if (depObj == null) yield break;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var children = child as T;
if (children != null)
yield return children;
foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
}
拨打强>
var children = this.FindVisualChildren<TextBox>();
foreach (var child in children)
{
child.Text = Settings.Default[child.Name].ToString();
}
答案 1 :(得分:1)
您可以将TextBox和字符串存储在如下列表中:
List<TextBox> TextBoxes = new List<TextBox>() {
tb1n,
tb2n,
tb3n,
...
};
List<string> mySettings = new List<string>(){
Settings2.Default.tb1n,
Settings2.Default.tb2n,
Settings2.Default.tb3n,
...
};
foreach (TextBox item in TextBoxes)
{
item.Text = mySettings[TextBoxes.FindIndex(a => a.Name == item.Name)];
}
然后你可以使用foreach循环给每个TextBox它的Text属性值。