Vlad M.
Vlad M.

Reputation: 89

How can i access from code behind, controls that are in a stack panel?

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.

Upvotes: 1

Views: 3759

Answers (3)

hellzone
hellzone

Reputation: 5246

Here is my solution

var child = (from c in theCanvas.Children
         where "someId".Equals(c.Tag)
         select c).First();

Upvotes: 1

Jens H
Jens H

Reputation: 4632

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?

Upvotes: 2

Tigran
Tigran

Reputation: 62296

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.

Upvotes: 4

Related Questions