Search code examples
xamlcontrolsdatatemplate

Access to controls inside a FlipView un XAML


In my Windows 8 app, I am trying to change the text of a textblock inside a DataTemplate of a FlipView...

my FlipView datatemplate (simplified...) :

        <FlipView.ItemTemplate>
            <DataTemplate>
                <TextBlock x:Name="test" />
            </DataTemplate>
        </FlipView.ItemTemplate>

I tried this solution : How do I access a control inside a XAML DataTemplate?

So my .cs :

        var _Container = flipView.ItemContainerGenerator.ContainerFromItem(flipView.SelectedItem);

        var _Children = AllChildren(_Container);


         var myTextBlock= _Children.OfType<TextBlock>().FirstOrDefault(c => c.Name.Equals("test"));

         myTextBlock.Text = "test";

with the method :

    public List<Control> AllChildren(DependencyObject parent)
    {
        var _List = new List<Control>();
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var _Child = VisualTreeHelper.GetChild(parent, i);
            if (_Child is Control)
                _List.Add(_Child as Control);
            _List.AddRange(AllChildren(_Child));
        }
        return _List;
    }

But I get a NullReferenceException error : "{"Object reference not set to an instance of an object."}" So it doesn't find my textblock...

Thanks


Solution

  • hello friend i have checked your code..and what i found is a very unnoticeable mistake..that is about the Control keyword..actually it is your type of control you want to search in your flipview..like textblock,textbox etc...you have to just change your AllChilderen Function like this and then all will work fine..

    public List<TextBlock> AllChildren(DependencyObject parent)
        {
            var _List = new List<TextBlock>();
            int j = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var _Child = VisualTreeHelper.GetChild(parent, i);
                if (_Child is TextBlock)
                    _List.Add(_Child as TextBlock);
                _List.AddRange(AllChildren(_Child));
            }
            return _List;
        }
    

    hope it will help you..