Reputation: 3270
I have a stackpanel that contains an Image and a TextBlock. I'm raising an event once double click is being performed by the user.(P.S - I'm adding the StackPanel and it's children (the Image and the TextBlock programatically if it matters).
Now, I need to get the TextBlock element from inside the stackpanel, I understand that I should do it using DataBinding, but I'm a beginner to WPF, and really haven't found any examples about it in the web. I'll be glad for an explanation, thank you very much!
(I learnt about DataBinding a while ago).
Upvotes: 9
Views: 23020
Reputation: 128146
A simple way of getting the first child element of a certain type (e.g. TextBlock) is this:
var textBlock = panel.Children.OfType<TextBlock>().FirstOrDefault();
You either get the first TextBlock or null
if there isn't any.
Upvotes: 22
Reputation: 3549
You need to DataBind TextBlock
Text
(?) element to your class - like so:
In XAML
<TextBlock x:Name="MyTextBlock"
Text={Binding ShowThis, Mode=OneWay} />
in class:
public class MyDataContextClass
{
private string showThis = string.Enpty;
public string ShowThis
{
get {return showThis;}
set
{
showThis = value;
if (PropertyChanged != null)
PropertyChanged(....);
}
}
}
and you must DataBing Xaml to class. (May be in constructor ?)
public class MyXamlWindow
{
public MyXamlWindow()
{
this.DataContext = new MyDataContextClass();
}
}
There's a lot of ways to do all above
Upvotes: 0