1

This is in C# in WPF:

I know I can add items to a stack panel like so: myStackPanel.Children.Add(new Button()); Or to a ListBox like so: myListBox.Items.Add(new Button()); Of course, I could edit beforehand the controls and add them latter, like set the proprieties first then add them.

But how do I select the control once it is in the stack layout with code behind. For example, is there a way similar to this: myStackPanel.Childern.CONTROL_AT_INDEX[n] ? And then how can I edit it even more like change the content of a label if it is a label or the event handler if it is a button ?

Also I want a solution for the ListBox as well please. I just don't know how to access those controls once they are inside.

thb
  • 13,796
  • 3
  • 40
  • 68
Vlad M.
  • 89
  • 1
  • 2
  • 10

3 Answers3

4

Assign to that controls x:Name and use that in your code behind.

This is naturally not valid for controls present in Templates and Styles.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • Well, thing is, I'm gonna add those controls at runtime so i can't add x:name to them can i ? i need a way of getting to those controls with out the help of the xaml part – Vlad M. Jul 04 '12 at 11:33
  • ah, if you need to that controls *at runtime* just preserve the objects you create, or give them *Name* and get them *by name* from the parent control. – Tigran Jul 04 '12 at 11:34
  • Yeah but still it's too easy i want to interact more with those controls, using names is just too damn simple :P isn't there a way to get down the hierarchy tree to the control i want ? – Vlad M. Jul 04 '12 at 13:30
  • You can make use of [Visual Tree](http://www.codeproject.com/Articles/21495/Understanding-the-Visual-Tree-and-Logical-Tree-in). But again it doesn't always work for *templates* and *styles*. – Tigran Jul 04 '12 at 13:48
2

Like Tigran already posted, is possible to assign an attribute to your controls in XAML:

<ListBox x:Name="myListBox"
         // more properties here...
/>

Then your code-behind will then be able to compile your line:

myListBox.Items.Add(new Button());

However, I strongly suggest you to alternativly use a MVVM approach to get rid of code-behind files. This reduces coupling of your business logic from the UI. Using the MVVM pattern is Microsoft's recommended way for working with WPF as it makes using many WPF feature very easy.

A great resource for Tutorials can be found int this SO thread, for example: MVVM: Tutorial from start to finish?

Community
  • 1
  • 1
Jens H
  • 4,590
  • 2
  • 25
  • 35
1

Here is my solution

var child = (from c in theCanvas.Children
         where "someId".Equals(c.Tag)
         select c).First();
hellzone
  • 5,393
  • 25
  • 82
  • 148