c# - Is it possible to use index in wpf control's name (e.g. TextBox(i)) to lessen code duplication? -


my application interface shown below: (ignore control names first)

enter image description here

when button1 clicked, outputbox1 display string in inputbox, same button2, when button2 clicked, outputbox2 display string in inputbox.

my question possible this: when button(i) clicked, outputbox(i).text = inputbox.text, there less code duplication..?

by way, simple illustration. real problem not simple (involve data binding listview). want know whether possible or not.

thanks suggestion , ideas.

  1. you can create own list of controls in code behind , use indexer of it.

    public partial class someview : usercontrol { private list<button> buttoncollection; private list<textbox> targetcollection;   public someview() {     initializecomponent();      buttoncollection = new list<button>     {         button1,         button2,         button3     };      targetcollection = new list<textbox>     {         outputtextbox1,         outputtextbox2,         outputtextbox3     }; }  private void buttonbase_onclick(object sender, routedeventargs e) {     var index = buttoncollection.indexof(sender button);      if (index >= 0)     {         var target = targetcollection[index];          ...     } } } 
  2. in xaml, if use mvvm , commands, can pass outbox elements in command parameter.

    <textbox name="outputtextbox1" /> <button name="button1"         command="{binding showtext}"         commandparameter="{binding elementname=outputtextbox1}" /> <textbox name="outputtextbox2" /> <button name="button2"         command="{binding showtext}"         commandparameter="{binding elementname=outputtextbox3}" /> <textbox name="outputtextbox3" /> <button name="button3"         command="{binding showtext}"         commandparameter="{binding elementname=outputtextbox2}" /> 

then in command handler:

    private void showtext(object obj)     {         var textbox = obj textbox;      } 
  1. if not, can store target elements in tag property:

    <textbox name="outputtextbox1" /> <button name="button1"         tag="{binding elementname=outputtextbox1}"         click="buttonbase_onclick" /> <textbox name="outputtextbox2" /> <button name="button2"         tag="{binding elementname=outputtextbox2}"         click="buttonbase_onclick"/> <textbox name="outputtextbox3" /> <button name="button3"         tag="{binding elementname=outputtextbox3}"         click="buttonbase_onclick"/> 

and handler this:

    private void buttonbase_onclick(object sender, routedeventargs e)     {         var target = (sender button)?.tag textbox;          if (target != null)         {             ...         }     } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -