访问Listbox DataTemplate中的控件

时间:2014-03-07 18:26:30

标签: windows-phone-7 windows-phone-8 listbox

我正在开发一个Windows Phone 8,我有一个选择列表框和这个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>

如何以编程方式访问selectedCheck CheckBox?

1 个答案:

答案 0 :(得分:1)

    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;
    }

用法:

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

但是,我认为你需要在IsChecked对象上绑定selectedCheck属性来操纵它

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