0

I'm a WPF noob, having moved from WinForms and I'm trying to access the text in a textbox by name with a string, basically I need the WPF version of Controls.Find() and I can't seem to find anything that works. Here's my code;

<TextBox x:Name="amplitude0" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" VerticalAlignment="Top" Width="100" Canvas.Left="160" Canvas.Top="64" />
<TextBox x:Name="amplitude1" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" VerticalAlignment="Top" Width="100" Canvas.Left="280" Canvas.Top="64" />

...up to amplitude9. and the C#;

object textBox = new TextBox();

        for (int n = 0; n <= 9; n++)
        {
            txtAmplitude = "amplitude" + n;
            textBox = FindName(txtAmplitude);
            amplitude[n] = textBox.text;
        }

I've tried different functions but can't find anything that works, can someone point me in the right direction?

Thanks in advance

3
  • What is your error? What doesn't work? Kind of hard to help without more information. Commented Jan 4, 2017 at 21:40
  • the error is in the "amplitude[n] = textBox.text;" line - "object does not contain a definition for text and no extension method text" Commented Jan 4, 2017 at 21:44
  • Where is amplitude[] defined? And FindName()? Commented Jan 4, 2017 at 21:48

1 Answer 1

1

Instead of

amplitude[n] = textBox.text;

what you want is amplitude[n] = ((TextBox) textbox).Text;

This is called casting.

But if you are doing this then you probably is not doing it right. I would suggest you to read more about MVVM design pattern since it is very different from Win form. What you are doing right now can be done easily and cleanly with Binding

Edit:

And object textBox = new TextBox(); is not needed. you don't need to initialize a new TextBox. Should be something like

TextBox textbox;
....
textbox = (TextBox) FindName(....);
Sign up to request clarification or add additional context in comments.

2 Comments

That's got it, thanks for your help! I'll have to read into it more, it's been a while since moving to new technology
I'll add on to this answer, instead of casting, the declaration line should be either var textbox = new TextBox()or TextBox textBox = new TextBox(); unless there is some other reason you want the variable to be an object.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.