Ahmed.C
Ahmed.C

Reputation: 487

How to access controls inside an ItemTemplate

Using Windows Phone 8, C#.

What I've done is basically done is edited the pivot item. I've named it MainPivot and inside that I've edited the Pivot Item Title and added a TextBlock inside it called PivotTitletxt. XAML for that is:

<DataTemplate x:Key="DataTemplate3">
  <TextBlock x:Name="PivotTitletxt" Height="34" TextWrapping="Wrap" Text="{Binding}" Width="447"/>
</DataTemplate>

How can I access this e.g. when setting opacity or changing foreground? so that I can use it on my MainPage like e.g. PivotTitletxt.Opacity = 30; ...

Thanks!

Upvotes: 0

Views: 214

Answers (1)

sexta13
sexta13

Reputation: 1568

The link @Sankarann gave you is a pretty good example.

I'll try to put it on your scenario:

Your MainPivot has PivotItems right? So What you have to do on the Loaded event is:

var _mainPivot = MainPivot as Pivot
foreach (var _pivotItem in _mainPivot.Items)
{
var _container = _mainPivot.ItemContainerGenerator.ContainerFromItem(_pivotItem);
var _children = AllChildren(_container)
var _name = "PivotTitletxt";
var _control = (TextBlock)_Children.first(x=>x.Name == _name);
_control.Opacity  = 30;

} 

Then copy the AllChildren method exactly as the it is in the site.

The code above, might have a few adjustments because I've done it without VS...

Hope it helps.

Regards,

============ new answer ==============

Find all controls in WPF Window by type

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

Then try :

TextBlock xx = FindVisualChildren<TextBlock>(mainPivot).FirsOrDefault(x=>x.name=="PivotTitletxt");

if(xx!=null)
xx.opacity = 30

Once again, this come might need some correction...i'm doing it by heart, without VS.

Try it out

Upvotes: 1

Related Questions