VansFannel
VansFannel

Reputation: 45911

Access a control inside a Listbox DataTemplate

I'm developing a Windows Phone 8 and I have a single selection Listbox and this DataTemplate:

<DataTemplate x:Key="LocalizationItemTemplate">
    <Border BorderBrush="Black" BorderThickness="2" CornerRadius="8" Background="#FF003847" Height="80">
        <Grid x:Name="contentGrid" Margin="4">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="10*"/>
                <ColumnDefinition Width="90*"/>
            </Grid.ColumnDefinitions>
            <CheckBox x:Name="selectedCheck" Content="CheckBox" HorizontalAlignment="Center" Height="20" Margin="0" VerticalAlignment="Center" Width="20"/>
            <TextBlock x:Name="locationName" TextWrapping="Wrap" Text="{Binding Name}" Margin="10,34,0,34" VerticalAlignment="Center" FontSize="24" Grid.ColumnSpan="2" Height="0"/>
        </Grid>
    </Border>
</DataTemplate>

How can I access the selectedCheck CheckBox programmatically?

Upvotes: 0

Views: 120

Answers (1)

Ku6opr
Ku6opr

Reputation: 8126

    private T FindElementInVisualTree<T>(DependencyObject parentElement, string name) where T : DependencyObject
    {
        var count = VisualTreeHelper.GetChildrenCount(parentElement);
        if (count == 0)
            return null;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parentElement, i);

            if (child != null && child is FrameworkElement && (child as FrameworkElement).Name.Equals(name))
            {
                return (T)child;
            }
            else
            {
                var result = FindElementInVisualTree<T>(child, name);
                if (result != null)
                    return result;

            }
        }
        return null;
    }

Usage:

ListBoxItem item = list.ItemContainerGenerator.ContainerFromItem(list.SelectedItem) as ListBoxItem;
CheckBox check = FindElementInVisualTree<CheckBox>(item, "selectedCheck");

But, I think you need to bind IsChecked property on selectedCheck object to manipulate on it

<CheckBox x:Name="selectedCheck" IsChecked={Binding Checked, Mode=TwoWay} ...

Upvotes: 1

Related Questions