How to get children of a WPF element

I have a stack panel containing Image and TextBlock. I raise an event when the user double-clicks twice. ( PS . I add a StackPanel and its children (Image and TextBlock programmatically, if that matters).

Now I need to get the TextBlock element inside the stack panel, I understand that I have to do this using DataBinding, but I am starting to work with WPF and really have not found any examples on the Internet. I will be happy to explain, thank you very much!

(I found out about DataBinding a while ago).

+7
source share
2 answers

An easy way to get the first child of a certain type (e.g. TextBlock) is to:

var textBlock = panel.Children.OfType<TextBlock>().FirstOrDefault(); 

You either get the first TextBlock, or null if it does not exist.

+17
source

You need a DataBind TextBlock Text (?) Element for your class - for example:

In xaml

 <TextBlock x:Name="MyTextBlock" Text={Binding ShowThis, Mode=OneWay} /> 

in the class:

  public class MyDataContextClass { private string showThis = string.Enpty; public string ShowThis { get {return showThis;} set { showThis = value; if (PropertyChanged != null) PropertyChanged(....); } } } 

and you need DataBing Xaml to class. (Maybe in the constructor?)

  public class MyXamlWindow { public MyXamlWindow() { this.DataContext = new MyDataContextClass(); } } 

There are many ways to do everything higher.

0
source

All Articles