2
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);

I don't want to repeat same code for all control types (setting tag and appending child to grid). Is there a way for that?

4
  • What's AutoSuggestionBox class?
    – D-Shih
    Nov 26, 2018 at 3:35
  • It would be great if you used real code. There's no .text property, for example. Nov 26, 2018 at 3:43
  • Sorry, updated the code Nov 26, 2018 at 4:02
  • @SHASHIKUMARS Ok I wrote an answer :)
    – D-Shih
    Nov 26, 2018 at 5:00

2 Answers 2

1

You can try to use the extract method to avoid duplicate code.

If you use children it might be UIElementCollection which add method need to pass System.Windows.UIElement class.

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;
}

Or you can try to use I saw you edit your question, you can try to use Dictionary be a mapper table then use TryGetValue to make it.

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);
}
0

Yes, just do this:

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.