Reputation: 373
I have the following item template (I tried to strip all the non relevant stuff):
<s:SurfaceWindow.Resources>
<ResourceDictionary>
<Style TargetType="{x:Type s:SurfaceListBox}">
<Setter Property="ItemTemplate">
<DataTemplate DataType="{x:Type local:myClass}"> //my own class
<s:SurfaceButton>
<TextBlock Text="{Binding name}"> //name is a string in my own class
//and close all the tags
The idea is that my listbox will contain buttons which are displaying some words on it.
Further down, I have a SurfaceListBox
using the above resource. I add in an item by:
myListBox.Items.Add(new myClass("My Name"));
And it would add a button to the listbox nicely, with the button displaying "My Name".
Now I need to change "My Name" to another string.
How do I access that TextBlock
?
I have tried googling but the solutions to access items in DataTemplate
they all require VisualTreeHelper.GetChildrenCount
via FindVisualChild
, which returns 0 for me so it doesn't work.
Upvotes: 0
Views: 139
Reputation: 30097
The simple and right way to achieve this is using DataBinding
.
Update the TextBlock XAML so that TextBlock can update itself whenever backend name
property changes
<TextBlock Text="{Binding name, UpdateSourceTrigger=PropertyChanged}">
In you myClass
implement INotifyPropertyChanged. Then whenever you wish to change the text call PropertyChanged
event.
public name
{
get
{
return _name;
}
set
{
_name = value;
PropertyChanged("name");
}
}
Upvotes: 2