var _textbox;
if (datatype == "STRING") {
_textbox = new TextBox();
_textbox.Text = "text";
}
else if (dataype == "ACTOR") {
_textbox = new AutoSuggestBox();
}
_textbox.Tag = "custom tag name";
grid.Children.Add(_textbox);
Grid.SetRow(_textbox, row);
我不想对所有控件类型重复相同的代码(设置标记并将子控件附加到网格(。有办法吗?
您可以尝试使用extract方法来避免重复代码。
如果使用children
,则可能是UIElementCollection,add
方法需要传递System.Windows.UIElement
类。
Control _textbox = GetTextBox();
_textbox.Tag = "custom tag name";
grid.Children.Add(_textbox);
Grid.SetRow(_textbox, row);
public Control GetControl(){
Control _textbox;
if (condition1) {
_textbox = GetTextBox();
}
else if (condition2) {
_textbox = new AutoSuggestBox();
}
return _textbox;
}
public TextBox GetTextBox(){
TextBox _textbox = new TextBox();
_textbox.Text = "text";
return _textbox;
}
或者你可以尝试使用我看到你编辑你的问题,你可以尝试用Dictionary
作为映射表,然后用TryGetValue
来制作它。
Dictionary<string, Control> dict = new Dictionary<string, Control>();
dict.Add("STRING", new TextBox() { Text = "text" });
dict.Add("ACTOR", new AutoSuggestBox());
Control _textbox;
if (dict.TryGetValue(datatype, out _textbox))
{
_textbox.Tag = "custom tag name";
grid.Children.Add(_textbox);
Grid.SetRow(_textbox, row);
}
是的,只需这样做:
Control _textbox = null;
if (datatype == "STRING")
{
_textbox = new TextBox();
_textbox.Text = "text";
}
else if (dataype == "ACTOR")
{
_textbox = new AutoSuggestBox();
}
if (_textbox != null)
{
_textbox.Tag = "custom tag name";
grid.Children.Add(_textbox);
Grid.SetRow(_textbox, row);
}